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.