c - 我的 C 代码 : wrong value output when I try to calculate Euler's number, e 有什么问题?

标签 c eulers-number

我正在尝试使用一个循环在 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/

相关文章:

c - 如何将另一个 c 文件的输出作为输入?

c - 如何修复此比较字符串(来自 argv 和 scanf)程序?

java - 提高欧拉数并行计算的性能

c++ - 在 C++ 中计算欧拉数

linux-kernel - 创建简单的内核模块

c - C 中的类型命名空间

code-generation - 使用Raku计算e数

Java:BigDecimal 错误地给出除以 0 的错误

objective-c - C 将函数调用作为变量传递