This should be solved in the pi.cpp.file. An approximate value of pi can be calc
ID: 3689128 • Letter: T
Question
This should be solved in the pi.cpp.file. An approximate value of pi can be calculated using the series given below: pi = 2 middot [ (2/1) * (2/3) * (4/3) * (4/5)#... * (2n/2n-1)*(2n/2n+1) ] (Wallis product) 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 of n until the user says she or he wants to end the program. The program should print a string of text to the terminal before getting each piece of input from the user. A session should look like the following example (including whitespace and formatting), with possibly different inputs and numbers in the output: 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) 3 The approximation is 3.56 using 3 terms. Enter the number of terms to approximate (or zero to quit) Each string printed by the program should include a newline at the end, but no other trailing whitespace. All approximated floating point numbers must be displayed to exactly two digits after the decimal point.Explanation / Answer
// Part 1 of Programming Assignment #3: http://koclab.cs.ucsb.edu/teaching/cs16/pa/pa03.html
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, num_terms;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
label_name:
while (1)
{
double pi = 0;
cout << "Enter the number of terms to approximate (or zero to quit): ";
cin >> num_terms;
if (num_terms == 0)
{
return 0;
}
if (num_terms == 1) {
for (i = 1; i <= num_terms; i++)
{
pi += pow(-1, i + 1) * 4.0 / (2 * i - 1);
}
cout << "The approximation is " << pi << " using " << num_terms << " term. ";
}
else if (num_terms > 1)
{
for (i = 1; i <= num_terms; i++)
{
pi += pow(-1, i + 1) * 4.0 / (2 * i - 1);
}
cout << "The approximation is " << pi << " using " << num_terms << " terms. ";
}
}
return 0;
}
sample output
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):
3
The approximation is 3.47 using 3 terms.
Enter the number of terms to approximate (or zero to quit):
0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.