-1

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;
}
  • 3
    Pro tip: https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems – πάντα ῥεῖ Sep 23 '20 at 19:29
  • 5
    Recommendation. Make a function. Move the pi-computing code into the function. Write a very simple `main` that calls the function over and over until the user doesn't input Y. Every value defined inside the function will be created anew on every function call, so if you initialize it correctly, it'll always start in a known, safe state. – user4581301 Sep 23 '20 at 19:29
  • Don't put the output part in the loop body... – JHBonarius Sep 23 '20 at 19:30

2 Answers2

1

You're not resetting your loop index. If I understand correctly your intent, you should add i = -1; in the true part of if (response == 'Y' || response == 'y').

The comment by user4581301 is also good advice.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Logicrat
  • 4,438
  • 16
  • 22
1

When your calculations run again in your for loop, the index starts at 1 instead of 0 because in for loops the (;;i++) happens after the code block, every time it loops. A super easy fix is to just assign i=-1; when you reset (I wouldn't recommend this dirty fix, it was to demonstrate the issue).

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
David Cho
  • 11
  • 2