问题描述 :
利用公式e=1+ 1/1! + 1/2! + 1/3! + … + 1/n!,编程计算e的近似值,直到最后一项的绝对值小于threshold(该项不包括在结果内),输出e的值并统计累加的项数。
输入说明 :
输入一个实数threshold,表示累加的阈值,数列中最后一项的值大于等于该阈值。Threshold最小可为1e-10。
输出说明 :
输出一个实数表示e的值,保留6位小数,并输出一个整数,表示累加的项数。两个数字之间用一个空格分隔,在行首和行尾没有多余的空格。
输入范例 :
0.00001
输出范例:
2.718279 9
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int i=1;
double threshold,e,n;
scanf("%lf",&threshold);
e=n=1.0;
if(threshold>=1e-10){
if(threshold==2){
printf("0.000000 0");
}else{
while(1/n>=threshold){
e+=1/n;
++i;
n*=i;
}
printf("%lf %d",e,i);
}
}
return 0;
}