c++求和 s=1+1/(1+2)+1/(1+2+3)+......+1/(1+2+3+4+5+.....+n) 求程序设计

建立一个NUM类,根据公式 计算S的值。例如,若n的值为11时,S的值为1.833333。具体要求如下:
私有数据成员。
int n :存放待求解的整数;
float S:存放根据上述公式所求的值。
公有数据成员。
NUM(int a):构造函数,初始化各数据成员;
void fun():根据上述公式求值并存放在S中;
void print():输出S中的值。
在主函数中对该类进行测试。定义一个NUM类的对象test,通过test调用成员函数按公式进行求值并输出。
将源程序取名为myfb.cpp。

#include <iostream>
#include <math.h>
using namespace std;
class Caculate{
private:
int n;
float sum;
public:
void NUM(int a);//:构造函数,初始化各数据成员;
void fun();//:根据上述公式求值并存放在S中;
void print();//:输出S中的值。
};
void Caculate::NUM(int a)
{
this->n=a;
this->sum=0;
}
void Caculate::fun()
{
this->sum=0;
int denominator=0;//分母的值
for(int i=1;i<=this->n;i++)
{
denominator+=i;
sum+=(1.0/denominator);//整形/整形=整形,所以必须要有一个数为浮点型
}
}
void Caculate::print(){
cout<<"总和为:"<<sum<<endl;
}
int main()
{
Caculate test;
test.NUM(11);
test.fun();
test.print();
getchar();
return 0;
}
温馨提示:答案为网友推荐,仅供参考