Question #46945

Write a program that will add the terms of an infinite geometric series. The program should read the first term (a) and the common ratio (r) for the series. It should then compute the sum in two ways: by formula ( s= a/(1−r) ),and by adding the individual terms until the answer agrees with the formula to 7 significant digits. Then print the formula answer, the answer found by adding the terms, and the number of terms that were added. Print the sums to at least ten places. Verify input with a while loop. Two real values are equal to n significant digits if the following condition is true: |a-b|<|a*10-n|.
the ratio should be -1 through 1 but not exactly equal -1 or for example .99999... would be the closet it would get to 1. runningTotal and currentTerm should be used. Don't use pow.
should be started something like this with these two libraries. and will use a while loop.
#include <iostresm>
#include <cmath>
using namespace std;
int main();
{

Expert's answer

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

double a;

double r;

cin >> a >> r;

if (fabs(r) < 1)

{

double sum1;

sum1 = a / (1 - r);

double currentTerm = a;

double runningTotal = 0;

int temp = 0;

while (((int)(runningTotal * 100000000)) % 10 == 0)

{

runningTotal += currentTerm;

temp++;

currentTerm *= r;

}

cout << sum1 << " " << runningTotal << " " << temp;

}

system("pause");

return 0;

}

#include <cmath>

using namespace std;

int main()

{

double a;

double r;

cin >> a >> r;

if (fabs(r) < 1)

{

double sum1;

sum1 = a / (1 - r);

double currentTerm = a;

double runningTotal = 0;

int temp = 0;

while (((int)(runningTotal * 100000000)) % 10 == 0)

{

runningTotal += currentTerm;

temp++;

currentTerm *= r;

}

cout << sum1 << " " << runningTotal << " " << temp;

}

system("pause");

return 0;

}

## Comments

## Leave a comment