We have to calculate sum of the terms of a series 1 + x + x^2 ...
..., for a given value of x. x is postive
but less than 1. Write a program to nd the sum by including all those terms, such that the dierence
between the last two terms included in the sum is less than 1.0E-8.
i have written the code it seems to work but it only outputs 6 digits but acc the question i need atlease 9-10 digits whats going wrong ??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <math.h>
usingnamespace std;
int main()
{ double x;
cout << "Enter a number < 1 : " ;
cin >> x ;
double sum = 0 ;
for(int i =0 ;pow(x,i-1) >= 1.0e-8 + pow(x,i) ;i++)
{
sum = sum + pow(x,i) ;
}
cout<< sum << endl;
}
Your code is pretty direct, but each term is calculated three times. In this case that's maybe not a big deal, though you may like to consider comparing with the saved value of the previous term each time rather than recalculating it.