The sum of a series can be computed as sum=x+x^2/2+x^3/3+x^4/4+x^5/5+⋯ ∞<x<∞ stopping when either n terms have been added or when the magnitude of a term in the series is less than 10-6, whichever comes first.
You are required to write a function, sumSeries, which given x, n returns the sum of the series. Use #include <cmath> and the abs function.
Do not use pow.
1
Expert's answer
2018-03-22T15:05:07-0400
#include <iostream> #include <cmath>
using namespace std;
double sumSeries(double, int);
int main() { int n; double x;
cout << "Please enter the value x: " << endl; cin >> x;
cout << "Please enter the number of terms (n): " << endl; cin >> n;
cout << "The sum of the series is " << sumSeries(x, n);
return 0; }
double sumSeries(double x, int n) { double xpow = x*x, sum = x;
for(int i = 2; i <= n; ++i) { sum += xpow / i; if(abs(xpow / i - xpow/(x*(i-1))) < 0.000001) break; xpow *= x; }
Comments
Leave a comment