题目:
A simple mathematical formula for e is
where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.
分析:
简单的阶乘求解。
三层循环,第一层循环n从0到9,第二层循环求和项的个数,第三层循环求阶乘。
本题的问题主要是0 1 2时输出形式不同,3-9时统一是9位小数。
C:printf("%d %.9lf\n",i,ans);
C++:cout<<i<<" "<<fixed<<setprecision(9)<<ans<<endl;
要加头文件#include <iomanip>
代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout<<"n e"<<endl;
cout<<"- -----------"<<endl;
cout<<"0 1"<<endl;
cout<<"1 2"<<endl;
cout<<"2 2.5"<<endl;
for (int i=3; i<=9; i++) {
double ans=1.0;
for (int j=1; j<=i; j++) {
int t=1;
for (int k=1; k<=j; k++)
t *= k;
ans += 1.0/t;
}
cout<<i<<" "<<fixed<<setprecision(9)<<ans<<endl;
}
return 0;
}