解决n!用C(方程误差在某处)

Den*_*nis 0 c math equation

在我学习C的过程中,我遇到了一个导致一些问题的任务.我需要为公式n!的近似值建立一个等式,可以描述为:

N!= n ^ n*e ^( - n)*sqrt(2(2*n + 1/3)*PI),但是我根本无法将我的值与实际值进行核对.5!= 120ish

我可以获得大约148的价值

无法弄清楚我的代码错误在哪里:

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

#define PI 3.14156
#define E_CONST 2.7828

int main ()
{

double num;
double calc, first, second, third, fourth;

printf("Give an int: ");
scanf("%lf", &num);


first = pow(num , num);

second = pow(E_CONST, -num);

third = (2 * num + 1/3);

fourth = sqrt(2*third*PI);

//calc = first * second * fourth;

calc = pow(num, num) * pow(E_CONST, -num) * sqrt(2*(2*num+(1/3))*PI);
printf("Input: %f", num);

printf("1: %.2f\n2: %.10f\n3: %.8f\n4: %.2f\n", first, second, third, fourth);

printf("\nInt was: %.2f\n\nApproximate number: %.5f", num, calc);

return 0;
}
Run Code Online (Sandbox Code Playgroud)

觉得我已经尝试了一切.代码有点混乱,但这是因为我现在已经用它拼写了这么多.

pmg*_*pmg 13

3.14156是一个坏的价值PI:它是更好地使用3.1416,或者3.14159,或者4 * atan(1),或者,对POSIX的实现,M_PI.

2.7828对于以下内容来说是一个非常糟糕的价值e:使用2.7183,或者exp(1),或者,对于POSIX实现更好M_E.

1/3是整数除法,结果为0:最好使用1.0/3.

你的近似也是不正确的.在正确的近似值

n^n * e^(-n) * sqrt((2*n+1/3)*PI)
Run Code Online (Sandbox Code Playgroud)

  • 为什么不简单地使用`math.h`中的`M_PI`宏? (2认同)

sta*_*lue 6

看来你陷入了整数除法陷阱1/3,它具有价值0.你需要用浮点常量来写这个1.0 / 3.0.

  • 我们大约每周一次,所以会有更多的机会. (2认同)