mardi 5 juillet 2016

How to reset values in for loop?

I need help figuring out where my code went wrong. I want to reset the values for the loop so that it isn't compiling because my output right now is using past input values in current calculation whereas I want the output to be different every time as though it is the firs time running the code. The code works fine when I don't use the while loop, but then I have to rerun the program each time. I want the output to prompt a new input every time, but not use past inputs in the new calculations. I know I'm not explaining it very well, but I'm just sort of lost. Anything helps!

This is my problem: An approximate value of pi can be calculated using the series given below:

pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 ... + (–1 ^ n)/(2n + 1) ]

Write a C++ program to calculate the approximate value of pi using this series. The program takes an input n that determines the number of terms in the approximation of the value of pi and outputs the approximation. Include a loop that allows the user to repeat this calculation for new values n until the user says she or he wants to end the program.

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
  int n;
  double sum=0;

  cout << "Enter the number of terms to approximate (or zero to quit):\n";
  cin >> n;

  if (n == 0)
    {
   return 0;
    }

  while (n != 0)
   {
     { for(int i=0;i<n;i++)
       {
         if (i%2==0)
           {
             sum += 1.0/(2*i+1);
           }
         else
           {
             sum += -1.0/(2*i+1);
           }
       }

    cout.setf(ios::showpoint);
    cout.precision(3);
    cout << "The approximation is " << sum*4 << " using " << n << " terms." << endl;
     }
    cout << "Enter the number of terms to approximate (or zero to quit):\n";
    cin >> n;
    }

return 0;
}

This is my output:enter image description here

This is what the output should be: enter image description here

Aucun commentaire:

Enregistrer un commentaire