在这个问题中,我们给数字n,它是级数1 /(1 * 2)+ 1 /(2 * 3)+…+ 1 /(n *(n + 1))的第n个项。我们的任务是创建一个程序来查找序列的总和。
输入值
n = 3
输出结果
0.75
解释- 总和= 1 /(1 * 2)+ 1 /(2 * 3)+ 1 /(3×4)=½+⅙+ 1/12 =(6 + 2 + 1)/ 12 = 9/12 = ¾= 0.75
解决此问题的简单方法是使用循环。并折算该系列中每个元素的值。然后将它们添加到总和值。
Initialize sum = 0 Step 1: Iterate from i = 1 to n. And follow : Step 1.1: Update sum, sum += 1/ ( i*(i+1) ) Step 2: Print sum.
该程序说明了我们解决方案的工作原理,
#include <iostream> using namespace std; double calcSeriesSum(int n) { double sum = 0.0; for (int i = 1; i <= n; i++) sum += ((double)1/(i*(i+1))); return sum; } int main() { int n = 5; cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n); return 0; }
输出结果
Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333
该解决方案使用循环,因此效果不佳。
解决该问题的有效方法是对级数和使用通用公式。
The series is 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + … n-th terms is 1/n(n+1). an = 1/n(n+1) an = ((n+1) - n) /n(n+1) an = (n+1)/n(n+1) - n/ n(n+1) an = 1/n - 1/(n+1) sum of the series is sum = 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + … Changing each term as in above formula, sum = 1/1 - ½ + ½ - ⅓ + ⅓ - ¼ + ¼ -⅕ + …. 1/n - 1/(n+1) sum = 1 - 1/(n+1) sum = (n+1 -1) / (n+1) = n/(n+1)
该程序说明了我们解决方案的工作原理,
#include <iostream> using namespace std; double calcSeriesSum(int n) { return ((double)n/ (n+1)); } int main() { int n = 5; cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n); return 0; }
输出结果
Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333