杭电acm1012 u Calculate e

 杭电acm1012                            

                                      u Calculate e

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18490    Accepted Submission(s): 8050


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
 


Source
 


Recommend
JGShining
 

 


 

 实现代码:

#include <iostream>
#include <iomanip> //设置cout输出格式 
using namespace std;

//求阶乘 
double fn(int k)
{
   double e;
   e =1; 
   while(k>0)
   {
      e*=(double)k;
      k--; 
   } 
   return e;   
}  
void main()

  int i;
  double sum[10]; 
  cout<<"n e"<<endl; 
  cout<<"- -----------"<<endl; 
  cout<<"0 1"<<endl;
  cout<<"1 2"<<endl;
  cout<<"2 2.5"<<endl; 
  sum[2]=2.5; 
  for(i=3;i<10;i++) 
  { 
     sum[i]=sum[i-1]+ double(1.0)/fn(i); 
     //setiosflags(ios::fixed)<<setprecision(9)表示输出小数点后的9位,不删除末尾多余的零 
        cout<<(int)i<<" "<<setiosflags(ios::fixed)<<setprecision(9)<<sum[i]<<endl;
   } 

 

 

附加:关于c/c++输出格式的控制

1.

printf("%.9lf/n",sum); 
//输出小数点后9位不省去末尾多余的0

2.

printf("%.10g/n",sum);

 //输出小数点后9位不省去末尾多余的0

3.

#include<iomanip>

cout<<setprecision(10)<<sum<<endl;

//输出小数点后9位省去末尾多余的0
4. 
#include<iomanip>

cout.precision(9);
cout <<setiosflags(ios::scientific)<<sum<<endl;

//输出小数点后9位省去末尾多余的0,并用科学计数法表示

5.

#include<iomanip>

cout.precision(9);

cout <<setiosflags(ios::fixed)<<sum<<endl;

//输出小数点后9位不省去末尾多余的0

6.

cout.precision(10);

cout.fixed;
cout<<sum<<endl;

//输出小数点后9位省去末尾多余的0  
7.

cout.precision(9);

cout <<fixed<<sum<<endl;

//输出小数点后9位不省去末尾多余的0

8:

cout<<setiosflags(ios::fixed)<<setiosflags(ios::right)<<setprecision(2);

setiosflags 是包含在命名空间iomanip中的C++ 操作符,该操作符的作用是执行由有参数指定

区域内的动作;

iso::fixed 是操作符setiosflags的参数之一,该参数指定的动作是以带小数点的形式表示浮点

数,并且在允许的精度范围内尽可能的把数字移向小数点右侧;

iso::right 也是setiosflags 的参数,该参数的指定作用是在指定区域内右对齐输出;

setprecision 也是包含在命名空间iomanip 中的C++ 操作符,该操作符的作用是设定浮点数;

setprecision(2) 的意思就是小数点输出的精度,即是小数点右面的数字的个数为2。

cout<<setiosflags(ios::fixed)<<setiosflags(ios::right)<<setprecision(2);

合在一起的意思就是,输出一个右对齐的小数点后两位的浮点数。

使用setprecision(n)可控制输出流显示浮点数的数字个数。C++默认的流输出数值有效位是6。


如果setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数。

setiosflags(ios::fixed)是用定点方式表示实数

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值