C++ 编写函数,计算1/1!+1/2!+1/3!+ … +1/n!。在主函数中输入n的值,调用函数完成计算并输出计算结果。

结果保留两位小数。
【输入/输出示例】

3↙
1.67

不是c语言 是c++哦

#include<iostream>
#include<cmath>
#include<iomanip>

double fun(int a);

int main()
{
using namespace std;
int n = 0;
double result;
cout << "Enter the number:";
cin >> n;
cin.get();
result = fun(n);
cout << setiosflags(ios::fixed) << setprecision(2) << result << "\n";


return 0;
}

double fun(int a)
{
double s = 0;
int i = 0, temp = 1;
for (i = 1; i <= a; i++)
{
temp *= i;
s += 1.0 / temp;
}
return s;
}

满足你要求了吧。嘿嘿!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-10-10
#include <iostream>
#include <iomanip>

using namespace std;
class TongXiangJiSuan
{
  public:
    int n;
    static int sum;
  private:
    int Account(void)
    {
        int i,j,temp;
        for(i=1; i<=n; i++)
        {
            for(j=1, temp=1; j<=i; j++)
                temp *= j;
            sum += 1/temp;            
        }
        return sum;
    }
}

int main(void)
{
  TongXiangJiSuan tx;
  cin >> tx.n;
  cout<<setiosflags(ios::fixed)<<setprecision(2)<<tx.Account()<<endl;
  return 0;  
}

追问

有错误...但非常感谢您   我c++学的太吃力

追答

恩。麻烦给采纳一下呗!

相似回答