You are invited to Log in or Register a free Frihost Account!

approximation of pi

umeshtangnu
I am trying to write a program the approximates pi and outputs each value of pi based on how many terms and how often (for instance if you entered 10 terms and for each 2 steps then pi would output
the 2nd term for pi
the 4th term for pi
the 6th term for pi
the 8th term for pi
the 10th term for pi

I am having a really hard time with getting the "number" (2,4,6,8,10) to output and getting the pi value to be accurate based on how often. I don't understand loops very well. Can anyone help me learn about them or help guide me in the right direction. (should I be using for loops or while loops or do while loops I have no idea)

 Code: #include #include #include using namespace std;     void printMessage(string);     int returnNumber(string); int main() {     char again;     int termspi,         steps,         num;     int countDenominator;     float pi = 0.0,              divisor = 0.0,           count;     const double NUMERATOR = 4.0;     cout << " Program will approximate Pi ";     cout << endl << endl;        termspi = returnNumber ("Enter the number of terms to use: ");     cout << endl << endl;     steps = returnNumber("Display Pi after every how many steps?: "); cout << "RESULTS" << endl; int interval; interval += steps;     for (count = 1.0, num = 1; num <= termspi; num++)          {         if (num % 2 == 0)            pi -= NUMERATOR/count;         else           pi += NUMERATOR/count;                      if (steps != 0)            steps = steps * interval;            interval +=1;         cout << fixed << showpoint;         cout << steps << " PI = " << setprecision(9) << pi << endl;         count += 2.0;         }      while (pi >= termspi) cout << pi << endl;         do {         cout << "Enter Y to run program again" << endl;         cout << "(or any other key to exit)" << endl;         cin >> again; }     while ((again == 'Y') || (again == 'y'));     return 1     ; }   void printMessage(string msg) {      cout << msg; }   int returnNumber(string msg) {      int num;      cout << msg;      cin >> num;            while (num < 1){          cout << "Your input is not valid !!!" << endl;          cout << "Please Re-enter a positive non zero number: ";          cin >> num;}          cout << endl;      return num; }