C++中1 / 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + n項之和


這裡,我們給定一個整數n。它定義了級數1/1 + ( (1+2)/(1*2) ) + ( (1+2+3)/(1*2*3) ) + … + n項的項數。

我們的任務是建立一個程式,求級數1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + … + n項的和。

讓我們舉個例子來理解這個問題:

輸入

n = 3

輸出

3.5

解釋:(1/1) + (1+2)/(1*2) + (1+2+3)/(1*2*3) = 1 + 1.5 + 1 = 3.5

解決這個問題的一個簡單方法是從1迴圈到n。然後,將i的和除以i的乘積的結果相加。

演算法

Initialise result = 0.0, sum = 0, prod = 1
Step 1: iterate from i = 0 to n. And follow :
   Step 1.1: Update sum and product value i.e. sum += i and prod *= i
   Step 1.2: Update result by result += (sum)/(prod).
Step 2: Print result.

示例

程式演示瞭解決方案的工作原理:

線上演示

#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
   double result = 0.0 ;
   int sum = 0, prod = 1;
   for (int i = 1 ; i <= n ; i++) {
      sum += i;
      prod *= i;
      result += ((double)sum / prod);
   }
   return result;
}
int main() {
   int n = 12;
   cout<<"Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto "<<n<<" terms is "   <<calcSeriesSum(n) ;
   return 0;
}

輸出

Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto 12 terms is 4.07742

更新於:2020年8月14日

888 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.