C++编程练习-求出e的值


Description
利用公式e = 1 + 1/1! + 1/2! + 1/3! + ... + 1/n! 求e 。
Input
输入只有一行,该行包含一个整数n(2<=n<=15),表示计算e时累加到1/n!。
Output
输出只有一行,该行包含计算出来的e的值,要求打印小数点后10位。
Sample Input
10
Sample Output
2.7182818011
Hint
1、e以及n!用double表示

2、要输出浮点数、双精度数小数点后10位数字,可以用下面这种形式:

参考代码

  1. #include <iostream>   
  2. #include <cstring>   
  3. #include <iomanip>   
  4. using namespace std;  
  5. double fact(int n){  
  6.     if(0 == n || 1 == n){  
  7.         return 1.0;  
  8.     }  
  9.     return (double)n * fact(n - 1);  
  10. }  
  11. int main(){  
  12.     int i,n;  
  13.     double ds;  
  14.     std::cin>>n;  
  15.     ds = 0;  
  16.     for(i = 0;i <= n;i ++){  
  17.         ds += 1.0 / fact(i);  
  18.     }  
  19.     std::cout<<std::fixed<<std::setprecision(10)<<ds<<std::endl;  
  20.     return 0;  
  21. }  

相关内容