C++ 中 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... 系列的和\n
在這個問題中,我們給定一個數字 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
解決該問題的一個簡單方法是使用迴圈。並計算級數中每個元素的值。然後將它們新增到 sum 值中。
演算法
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP