Given “n” by the user, this program will calculate pi based in n terms. This program ****ed me over because i thought it was asking to calculate it to n decimal places, but its really using an infinite series. So the more numbers you put it, the more accurate our estimation of pi will be.
Ex.
Inputting 10 , we get 3.232323 ( not very close )
Inputting 500, we get 3.14359 ( getting closer )
Inputting 99999, we get 3.14158 ( good enough! )
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char run;
do{
//variable delcarations
int n;
double sum(0.0), pi;
//input
do {
cout << "This program will calculate pi based on n terms." << endl;
cout << "Enter number of terms to calculate pi to: " << endl;
cin >> n;
if (n < 0) cout << "ERROR! Invalid Input. Try again." << endl;
else if (n == 0) cout << "That wouldnt work now, silly :-)" << endl;
} while (n < 0 || n == 0);
//processing
for (int i = 0; i <= n; i++)
{
sum = sum + pow(-1, i)/(2*i+1);
}
pi = 4 * sum;
cout << "Using " << n << " terms to calculate pi, we have exstimated pi at " << pi << endl;
//run again?
cout << "Run program again? " << endl;
cin >> run;
} while (run == 'y' || run == 'Y');
}