2

I'm in an introductory C++ class at my university. We were assigned a project to create a program to approximate pi using a series where pi=summation ((-1)^i+1)*(4/2i-1).

I need my output to look like this:

This program approximates pi using an n-term series expansion.
Enter the value of n> 6
pi[6] = 4[1-1/3+1/5-1/7+1/9-1/11] = 2.9760461760417560644

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
int numOfTerms;
cout <<"This program calculates pi using an n-term series expansion."<<endl;
cout <<"Enter the value for n>";
cin >>numOfTerms;

if (numOfTerms<=0)
    cout <<numOfTerms<<"is an invalid number of terms."<<endl;
else
{
    cout <<"pi["<<numOfTerms<<"] = ";
    int i;
    for (i=1; i<=numOfTerms; i++)
    {   
        double pi, sum, firstTerm, secondTerm;
        firstTerm=pow(-1,(i+1));
        secondTerm=1/(2*i-1);
        pi=firstTerm*secondTerm;
        {
            if (pi <= 4)
                cout <<firstTerm<<"/"<<secondTerm;
            else
                cout <<"You have a C++ math error.";
        }
        sum=sum+(4*pi);
        cout <<" = "<<sum<<endl;
    }   
}
return 0;
}   

I have an earlier version of the code that correctly sums the n-series approximation but it does not display expanded series that equals the sum.

My current version does not display the correction summation, but it display pi[n] on the screen n times over n lines.

I'm willing to try to figure the majority of the project on my own, I just need to know if there is a way to get the output of my loop to display on one line instead of each iteration displaying on its own line.

3 Answers3

4

Dont use endl and your job will be done.

endl

Inserts a new-line character and flushes the stream.

Its behavior is equivalent to calling os.put('\n') (or os.put(os.widen('\n')) for other character types), and then os.flush().

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

Three things: First, change your calculation of secondTerm for the following:

secondTerm=1.0/(2*i-1);

This way, you are forcing it to be a double (otherwise, it would return an int, which we do not want). Second, change this line:

cout <<firstTerm<<"/"<<secondTerm;

for this line:

cout <<pi;

That is because secondTerm holds the result of the division, not the denominator.

Third, move this line:

cout <<" = "<<sum<<endl;

after the for loop, because that prints the final result, which you would do after you sum all the terms. Having that line inside the for is causing the line breaks. If you do this, you will need to move this line:

double pi, sum, firstTerm, secondTerm;

before the for loop, so the sum variable continues to exist afterwards.

If you do all this, the program will work fine (although it prints all the terms without any spaces between them).

memo1288
  • 748
  • 1
  • 6
  • 12
1

Don't use endl. This causes a line-break.

Will Custode
  • 4,576
  • 3
  • 26
  • 51