Reputation: 11
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;
}
Upvotes: 0
Views: 3606
Reputation: 186678
You have wrong initialization:
double sum=0.0;
int sign=1;
It should be
double sum = 1.0;
int sign = -1;
The loop is also wrong (has a typo?), it should be
for (int i = 1; i < n; i++) { /* please, notice "i < n" and "{" */
sum += sign / (2.0 * i + 1.0);
sign = -sign; /* more readable, IMHO than sign *=-1; */
}
pi = 4.0 * sum; /* you can well move it out of the loop */
EDIT if you want to repeat calculation a common practice is extrating a function (do not cram everything into single main
):
double compute(int n) {
if (n < 0)
return 0.0;
double sum = 1.0;
int sign = -1;
for (int i = 1; i < n; i++) {
sum += sign / (2.0 * i + 1.0);
sign = -sign; /* more readable, IMHO than sign *=-1; */
}
return 4.0 * sum;
}
EDIT 2 the main
function could be something like this:
int main() {
int n = -1;
/* quit on zero */
while (n != 0) {
cout << "Enter the number of terms to approximate (or zero to quit):" << endl;
cin >> n;
if (n > 0)
cout << "The approximation is " << compute(n) << " using "<< n << " terms" << endl;
}
}
Upvotes: 1
Reputation: 1189
The alternating sign must be part of your loop. Include it into the loop body by using a compound statement:
for (int i=1; i <=n; i++) {
sum += sign/(2.0*i+1.0);
sign *=-1;
}
Upvotes: 0