C++程序找出1 + x / 2的总和!
在本教程中,我们将讨论一个寻找1+x/2之和的程序!+x^2/3!+…+x^n/(n+1)!
为此,我们将获得x和n的值。我们的任务是在给定的序列中相应地计算值并找到其总和。
示例
#include <iostream>
#include <math.h>
using namespace std;
//finding factorial of a number
int fact(int n) {
if (n == 1)
return 1;
return n * fact(n - 1);
}
//calculating the sum
double sum(int x, int n) {
double i, total = 1.0;
for (i = 1; i <= n; i++) {
total = total + (pow(x, i) / fact(i + 1));
}
return total;
}
int main() {
int x = 5, n = 4;
cout << "Sum is: " << sum(x, n);
return 0;
}输出结果
Sum is: 18.0833