在本教程中,我们将讨论一个寻找序列1 +½+?的和的程序。+¼+…+ 1 / n
为此,我们将获得n的值。我们的任务是计算达到给定值的序列之和并将其打印出来。
#include <iostream> using namespace std; //returning the sum of given series class sum_series { public : double sum(int n) { double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return s; } }; int main() { sum_series g; int n = 5; cout << "Sum is " << g.sum(n); return 0; }
输出结果
Sum is 2.28333