如何修复"e = 1 + 1/1!+ 1/2!+ 1/3!+ ...... + 1/n!"的代码?

Ans*_*_42 6 c

这就是我想出的:

#include <stdio.h>

int main (void)
{
  int n, i, j;
  float e = 1.0, nFact = 1.0;

  printf ("please enter the number");
  scanf ("%d", &n);

  for (i = 1; i <= n ; i++)
  {
    for (j = 1; j <= i; j++)
    {
      nFact *= j;
    }
    e = e + (1.0 / nFact);
  }

  printf ("The value of 'e' is : %f", e);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我从这段代码中得到的.输入:3输出:2.58333(接近2.6666 ...)

但是对于n = 3,e应该给出2.6666 ..作为值.

我在这里做错了吗?如何获得正确的输出?

Hen*_*rik 15

你不必要地在每次迭代中计算阶乘.只需更换内循环nFact *= i;.

#include<stdio.h>

int main (void)
{
int n,i,j;
float e=1.0, nFact=1;

printf("please enter the number");
scanf("%d", &n);

for( i =1; i<= n ; i++)
{
    nFact*=i;
    e = e + (1.0/ nFact);
}

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

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


hus*_*sik 13

Am i doing something wrong here?

您忘记将factorial变量设置为1.所以,你的变量很快变小了.这使得(1.0/nFact)更小,这就是为什么你会变小e.

nFact=1.0;     //add this line so it resets to 1.0 everytime a factorial is needed
for( j = 1  ; j <= i; j++)
{
    nFact *= j;
    e = e + (1.0/ nFact);
}
//only single loop is more than enough
Run Code Online (Sandbox Code Playgroud)

你通过O(n)复杂性获得了阶乘.为什么不保存旧值并在每次迭代中使用它?(O(1)--->不需要阶乘循环.只需使用旧值,因为你没有重置它.(只需乘以i)

how can i get the proper output?

在第11次或第12次迭代之后,您float将无法提供足够的精度分辨率 - 最小步骤.如果你想要科学,Double或者B?gDecimal似乎更好