利用e=1+1/1!+1/2!+...+1/n!,编程计算e的近似值,直到最后一项的绝对值小于10^-5为止,输出e的值并统计累加的项数。
(我用外部函数定义了阶乘,这样使得逻辑更加清晰明了,也可以将阶乘写入循环中,亦可实现。)
参考代码:
#include<stdio.h>
#include<math.h>
long fact(long a); //声明定义函数
int main(void)
{
int count=1;
long a=1;
double e=1.0;
do {
e = e + (1.0 / fact(a));
a++;
count++;
} while (fabs(1.0 / fact(a-1))>=1e-5);
printf("e的估计值为:%lf,累加的项数为:%d\n", e, count);
printf("%ld",fact(5));
return 0;
}
long fact(long a) //构造外部阶乘函数
{
int i;
long b=a;
for (i = 1; i <b; i++)
{
a = a * i;
}
return a;
}
参考截图:(截图中有错误(打错了,在此纠正):for循环内部应该为:i<b)