21: 計算e


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 <stdio.h>
#include <math.h>
int main()
{
	double threshold;
	double e = 1.0, n = 1.0, m = 1.0;
	scanf("%lf", &threshold);
	if (threshold > 1.0)
	{
		printf("0.000000 0");
	}
	else
	{
		while (fabs(1 / m) >= threshold)
		{
			m = 1.0;
			for (double i = 1.0; i <= n; i++)
			{
				m *= i;
			}
			if (fabs(1 / m) >= threshold)
			{
				e += fabs(1 / m);
				n++;
			}
		}
printf("%.6lf %d", e, (int)n);
 
	}
        return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM