利用公式 e = 1 + 1/1! + 1/2! + 1/3! + ... + 1/n! 計算 e 的近似值。
輸入一行整數 n(2 ≤ n ≤ 15),表示累加到 1/n!。輸出 e 的值,必須印出小數點後 10 位。
樣例輸入 10,輸出 2.7182818011。
cout << fixed << setprecision(10) 或 printf("%.10f", e)。另外,寫成遞迴階乘雖然直觀,但每次迴圈都重算一次 n!,總量是 O(n²)。改為「一邊除、一邊累乘分母」可以降到 O(n):維護一個 term,初始為 1,每次 term /= i 再累加,就是同一條級數。
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
double fact(int n){
if (0 == n || 1 == n) {
return 1.0;
}
return (double)n * fact(n - 1);
}
int main(){
int i, n;
double ds;
std::cin >> n;
ds = 0;
for (i = 0; i <= n; i++) {
ds += 1.0 / fact(i);
}
std::cout << std::fixed << std::setprecision(10) << ds << std::endl;
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int n;
double e = 1.0, term = 1.0;
cin >> n;
for (int i = 1; i <= n; ++i) {
term /= i; // term 就是 1/i!
e += term;
}
cout << fixed << setprecision(10) << e << endl;
return 0;
}
順帶一提,n 只要到 10 左右,double 的精度就已經逼近極限,再往上加項數幾乎不會改變前 10 位,這也是樣例用 n=10 的原因。