Working on a C++ program that calculates the value of pi. I can run it once correctly and it will output the desired value. But the part of the program where it asks the user if they want to run again, that value of pi will not be correct according to the formula. I can't seem to figure out where I am going wrong here.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int seqNum; // Declares variable for user input
char response; // Will hold char if user wants to rerun the program or not.
// Welcome Message and prompts user to input an integer
cout <<"Welcome to the Calculating Pi Program!\n";
cout <<"Please enter an integer greater than 0: \n";
// Assigns user input to the seqNum variable
cin >> seqNum;
// While loop to validate user input
while (seqNum < 1)
{
cout <<"ERROR: You must enter an greater than 0\n";
cout <<"Please enter an integer greater than 0: \n";
cin >> seqNum;
}
double pi = 0;
for (int i=0; i <= seqNum; i++)
{
double sum = 1.0/(2*i+1);
if (i % 2 == 0)
pi += sum;
else
pi -= sum;
if (i == seqNum)
{
pi *= 4;
cout << fixed << setprecision(50) << pi << endl;
pi = 0;
i = 0;
cout << "Do you want to run again (Y/N):";
cin >> response;
if (response == 'Y' || response == 'y')
{
cout << "Please enter an integer greater than 0: \n";
cin >> seqNum;
}
else
return 0;
}
}
return 0;
}