C++ 中 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n 級數的和


在這個問題中,我們給定兩個數字 X 和 n,它們表示一個數學級數。我們的任務是建立一個程式來找到級數 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n 的和。

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

輸入

x = 2 , n = 4

輸出

解釋 -

sum= 1 + 2/1 + (2^2)/2 + (2^3)/3 + (2^4)/4
   = 1 + 2 + 4/2 + 8/3 + 16/4
   = 1 + 2 + 2 + 8/3 + 4
   = 9 + 8/3
   = 11.666.

一個簡單的解決方案是建立級數並使用基值 x 和範圍 n 找到和。然後返回總和。

示例

程式說明我們解決方案的工作原理,

 線上演示

#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
double calcSeriesSum(int x, int n) {
   double i, total = 1.0;
   for (i = 1; i <= n; i++)
   total += (pow(x, i) / i);
   return total;
}
int main() {
   int x = 3;
   int n = 6;
   cout<<"Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^"<<n<<"/"<<n<<" is "<<setprecision(5)   <<calcSeriesSum(x, n);
   return 0;
}

輸出

Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^6/6 is 207.85

更新於: 2020年8月14日

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.