杭电1012——终于学会用C++保留小数了

来源:互联网 发布:怎么查ftp的端口号 编辑:程序博客网 时间:2024/06/05 07:01

u Calculate e

Problem Description
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.
 


 

Output
Output the approximations of e generated by the above formula for the values of n from 0 to 9. The beginning of your output should appear similar to that shown below.
 


 

Sample Output
n e- -----------0 11 22 2.53 2.6666666674 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;
}

原创粉丝点击