这就是我想出的:
- #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;
- }
这是我从这段代码中得到的.
输入:3
产量:2.58333(接近2.6666 …)
但是对于n = 3,e应该给出2.6666 ..作为值.
我在这里做错了吗?如何获得正确的输出?
解决方法
你不必要地在每次迭代中计算阶乘.只需用nFact * = i;替换内部循环.
- #include<stdio.h>
- int main (void)
- {
- int n,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;
- }