u Calculate e
where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.
n e - ----------- 0 1 1 2 2 2.5 3 2.666666667 4 2.708333333
分析:就是输出从0到9的值。开始不会用c++取小数
用了cout <<setprecision(9)<<s+1/jie(i)<<endl;来取,但是输出结果就只有八个小数!
不明白就把setprecision(9)改为了setprecision(10),结果更坑爹,虽然好多有九个小数了,但是!!n=8时,却是个例外,输出了八个,最后一个本来是零,却没有输出!
十分不理解,就百度了一下,好像自己错了,发现自已好白痴!setprecision只是控制输出流显示浮点数的数字个数,fixed合用的话,才可以控制小数点右面的位数!!
改为setiosflags(ios::fixed)<<setprecision(9)就行了!
代码:
#include<iostream>
#include<iomanip>
using namespace std;
double jie(double n)
{
if(n==1)
return 1;
else
return n*jie(n-1);
}
int main()
{
cout<<"n"<<" "<<"e"<<endl;
cout<<"- -----------"<<endl;
cout<<0<<" "<<1<<endl<<1<<" "<<2<<endl<<2<<" "<<2.5<<endl;
double s=2.5;
for(int i=3;i<=9;i++)
{
cout<<i<<" ";
cout<<setiosflags(ios::fixed)<<setprecision(9)<<(s+1/jie(i))<<endl;
s+=1/jie(i);
}
return 0;
}