在这个问题上,我们给了两个数字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