C : 我的 'Poisson calculator' 给我#1.INF00。为什么会这样?

C : My 'Poisson calculator' gives me #1.INF00. Why does this happen?

首先,这是我的代码:

#include <stdio.h>
#include <conio.h>
#include <math.h>

main()
{
    float Exp, Act, Px, Facto_Act;
    printf("\n This is Poisson Distribution Calculator!");
    printf("\n Enter the expected value of success in a time period:");
    scanf("%f",& Exp);
    printf("\n Enter the actual or calculated value of success in a time period:");
    scanf("%f",& Act);
    Px=pow(M_E,-Exp)*pow(Exp,Act)/Facto_Act;
    printf("\n Poisson probability is:%f", Px);
    getch();
    return 0;
}

Facto_Act(float Act)
{
    float c;
    float result=1;
    for(c=1;c<=Act;c++)
        result=result*c;
    return result;
}

进一步说明:

泊松方程如下所示:

P(x)= (e^-Lambda)(Lambda^x)/(x!)

Exp:给定时间内的预期事件数(Lambda) Act:给定时间内实际发生的事件数(x) Px:事件在给定时间内发生的概率(P(x)) Facto_Act:给定时间内实际事件数的阶乘 (x!)

当我弄清楚如何在 C 中对整数进行阶乘时,我也会尝试为正小数添加阶乘。但是#1.INF00 不是我期望的值。

当我编译代码时,不再显示编码错误。但是当我输入一段时间内成功的预期值,然后输入一段时间内成功的实际值时,我总是以#1.INF00 结尾。我对 C 很陌生,虽然这个站点帮助我改进了我的程序,但我无法理解“#1.INF00”的意思。

我决定不让Facto_Act成为函数

我决定通过不使 Facto_Act 成为函数然后尝试调用它来规避整个 Facto_Act 函数问题。似乎可以在不为其创建新功能的情况下执行阶乘。因此 Facto_Act 现在是一个变量。这是我的新代码:

#include <stdio.h>
#include <conio.h>
#include <math.h>


main()
{
    double Exp, Px;
    int c, Act, Act2, Facto_Act=1;
    printf("\n This is Poisson Distribution Calculator!");
    printf("\n Enter the expected value of success in a time period:");
    scanf("%lf",& Exp);
    printf("\n Enter the actual or calculated value of success 
    \n in a time period(must be an integer!):");
    scanf("%d",& Act);
    /*My factorial starts here*/
    for (c=1;c<=Act;c++)
        Facto_Act=Facto_Act*c;
    /*My factorial ends here*/
    Px=(pow(M_E,-Exp))*(pow(Exp,Act))/Facto_Act;
    printf("\n Poisson probability is:%lf", Px);
    getch();
    return 0;
}

感谢大家对我的帮助。

您声明了一个名为 FactoAct 的浮点型变量。由于它是一个没有初始化的外部变量,所以它的值为 0。

稍后您定义一个函数 Facto_Act(float Act),其隐式 return 类型为 "int"。

您的除法 xxx / FactoAct 将 xxx 除以变量 FactoAct,该变量为零。这就是您的 INF 结果的来源。

当函数位于顶部时,当编译器看到 xxx / FactoAct 时,FactoAct 不是函数调用的结果,而是函数本身。您不能将数字除以函数。这没有意义。函数唯一能做的就是获取它的地址,或者调用它。

您可能需要 FactoAct (x) 或类似的东西。

PS。不要使用 float 而不是 double,除非你有理由可以清楚地说明为什么在你的特定情况下 float 比 double 更好。