C语言求'e'的近似值

Finding approximate value of 'e' in C language

我正在尝试使用 C 程序找到 'e' 的近似值。我正进入(状态 无论我输入 n 的值是什么,e 的值都为真。请让我 在我的代码中找到错误。

#include <stdio.h>

int f;
int k;

int factorial (int f);

int main () { 
    int n,i;

    int e = 1;

    printf("Enter the value of n:");
    scanf("%d",&n);

    for (i = 1; i <= n; i++) {
        e = e + (1/factorial(i));
    }

    printf("The value of e is %d",e);

    return(0);
}

int factorial (int f) {    
    for (k = 1; k <= f; k++) {
       f = f*k;
    }

    return(p);
}

您有一些 errors.You 在 int 变量中添加浮点值!请阅读以下代码的注释:

int k; // remove f

int factorial (int f);

int main () {

int n,i;

float e=1; // take e as float/double, not int

printf("Enter the value of n:");

scanf("%d",&n);

for (i=1 ; i<=n ; i++) {

    e=e+(1.0/factorial(i)); // take 1.0 (floating value) instead of 1 (integer value)
}

printf("The value of e is %f",e);

return(0);
}

int factorial (int f) {
    int total=1; // initialize total with 1
    for (k=1 ; k<=f ; k++) {

        total=total*k; // here is a big mistake in your code. You incremented value of f in every iteration. Try to print value of f after every iteration to find your error.
    }

    return(total);
}

如前所述,您必须使用浮点变量。还有一个问题就是阶乘函数在12之后会溢出!此外,不断地重新计算阶乘是一种处理能力的浪费。这显示了一种更有效的方法来实现泰勒级数,即建立在前一项的基础上。这也回避了计算阶乘的问题。

#include <stdio.h>

int main(void) {
    double e, term;
    int t, n;

    printf("Enter the value of n:");
    if(scanf("%d", &n) != 1) {
        return 1;
    }

    e = 1;
    term = 1;
    for(t = 1; t <= n; t++) {
        term /= t;
        e += term;
    }
    printf("%.15f\n", e);
    return 0;
}

使用您的程序可以处理的最大值n程序输出

Enter the value of n:12
2.718281828286169

而在 math.h 中是

2.718281828459045...

这不是很准确。此示例允许获得更准确的值:

Enter the value of n:20
2.718281828459046
double factorial (int f) {
    double p = 1;
    for (k = 1; k <= f; k++) {
        p = p*k; // f = f * k;
    }

    return p; // what is p doing here? (in original code)
}

你的问题是你正在改变 f 的值,除此之外其他错误已经解释过了。它应该 return double 和其他一些错误。

为了准确 float 估计,

e = (((((((((1.f / 11 + 1) / 10 + 1) / 9 + 1 ) / 8 + 1) / 7 + 1) / 6 + 1) / 5 + 1) / 4 + 1) / 3 + 1) / 2 + 2

首字母.f必不可少。


从最小值开始累积会好很多。