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表示
利用公式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位数字,可以用下面这种形式:
参考代码
#include <iostream> #include <cstring> #include <iomanip> using namespace std; double fact(int n){ if(0 == n || 1 == n){ return 1.0; } return (double)n * fact(n - 1); } int main(){ int i,n; double ds; std::cin>>n; ds = 0; for(i = 0;i <= n;i ++){ ds += 1.0 / fact(i); } std::cout<<std::fixed<<std::setprecision(10)<<ds<<std::endl; return 0; }