我正在尝试使用一个循环在 C 中逼近欧拉数,该循环在 e 的两个连续值之间的差值小于 0.0000001 时终止。我得到的值是 2.99.. 我尝试设置它以便在每次迭代时将 e 与它自身的先前值(保存在 e1 中)进行比较,如果差异大于 0.0000001,它将添加另一个项 1/(不!)。有什么问题?我是编程新手,因此欢迎任何建议/批评。
#include <stdio.h>
int main()
{
float e1 = 0, e2 = 1;
int n = 1, nfact;
while ((e2 - e1) > 0.0000001)
{
e1 = e2;
nfact = 1;
for (int count = 1; count < n; count++)
{
nfact = n * count;
}
n = n + 1;
e2 = e1 + (1.0 / nfact);
}
printf("Approximated value of e = %f", e2);
return 0;
}
最佳答案
nfact = 1;
for (int count = 1; count < n; count++)
{
nfact = n * count;
}
不会计算 n!
。
nfact 每次迭代都会获得一个全新的值。
你的意思当然是
nfact = 1;
for (int count = 2; count <= n; count++)
{
nfact *= count;
}
关于c - 我的 C 代码 : wrong value output when I try to calculate Euler's number, e 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693329/