21 計算e
作者: Turbo時間限制: 1S章節: 循環
問題描述 :
利用公式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<math.h>
const double eps = 1e-8
#define Equ(a,b) (fabs((a)-(b))<(eps))
#define Less(a,b) ((a)-(b)<(-eps))
#define More(a,b) ((a)-(b)>(eps))
#define LessEqu(a,b) ((a)-(b)<(eps))
#define MoreEqu(a,b) ((a)-(b)>(-eps))
本題還要特別注意Threshold>1的情況。
代碼
#include<stdio.h>
const double eps = 1e-11;
#define More(a,b) ((a)-(b)>(-eps))
#define Less(a,b) ((a)-(b)<(-eps))
double factoria(int n){
double nn = (double)n;
int i;
for(i=n-1;i>=1;i--)
nn *= (double)i;
return nn;
}
int main(){
double t;
scanf("%lf",&t);
if(Less(1.0,t))
printf("0.000000 0\n");
else{
int n=1;
double e = 1 ;
while(More(1.0/factoria(n),t)){
e += 1/factoria(n);
n++;
}
printf("%.6f %d\n",e,n);
}
return 0;
}