gpt4 book ai didi

c - 解决 n!用C(某处方程错误)

转载 作者:太空宇宙 更新时间:2023-11-04 05:01:39 24 4
gpt4 key购买 nike

在我学习 C 的过程中,我遇到了一个给我带来一些问题的任务。我需要对公式 n! 的近似值做一个等式,可以描述为:

n! = n^n*e^(-n)*sqrt(2(2*n+1/3)*PI),但是我根本无法让我的值与实际值相符。 5! = 120ish

我可以得到大约 148ish 的值

无法找出我的代码哪里错了:

#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;
}

感觉我什么都试过了。代码有点乱,但这是因为我现在已经乱七八糟了。

最佳答案

3.14156PI 的错误值:最好使用 3.1416,或 3.14159,或 4 * atan(1),或者,对于 POSIX 实现,M_PI

2.7828e非常差值:最好使用 2.7183 exp(1),或者,对于 POSIX 实现,M_E

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

您的近似值也不正确。 correct approximation

n^n * e^(-n) * sqrt((2*n+1/3)*PI)

关于c - 解决 n!用C(某处方程错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7359935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com