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.
The expect result is: Enter the number of terms to approximate (or zero to quit): 1 The approximation is 4.00 using 1 term. Enter the number of terms to approximate (or zero to quit): 2 The approximation is 2.67 using 2 terms. Enter the number of terms to approximate (or zero to quit): 0
I can get the correct result now but I don't know how to 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 <stdio.h> #include <iostream> #include <cmath> using namespace std; int main() { int n; double pi, sum; do { cout << "Enter the number of terms to approximate (or zero to quit):" << endl; cin >> n; if (n >0) { double sum=1.0; int sign=-1; for (int i=1; i <=n; i++) { sum += sign/(2.0*i+1.0); sign=-sign; } pi=4.0*sum; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "The approximation is " << pi << " using "<< n << " terms" << endl; } } while(n>0); cout << endl; return 0; }
sign *=-1;->sign=-signwould be better