Need help with this C++ code! PI.CPP Write a C++ program that approximates the v
ID: 3817098 • Letter: N
Question
Need help with this C++ code!
PI.CPP Write a C++ program that approximates the value of the constant r, based on the Leibniz formula for TL. The formula is shown in the image below: 4 Put another way, the formula can be written as: pi-4.[1-1/3 1/5-1/7+19...1 A n)/(2n+1)1 The Leibniz formula works well for high values of n. The program takes an input from the user for the value of n, which determines the number of terms in the approximation of the value of pi. The program then outputs that calculation. You must also 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 by issuing an input of 0. 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 various and different inputs and numbers in the output:Explanation / Answer
//Program to Calculate pi value using Leibniz series
#include <iostream>
#include <iomanip>
using namespace std;
double calculatePI(int n)
{
double sig = 1; //For the next iteration
double piValue = 0;
for( double i = 1; i <= (n * 2); i += 2){ //Calculate pi value using Leibniz series
piValue = piValue + sig * (4 / i);
sig = -sig;
}
return piValue;
}
int main()
{
int n;
do{
cout<<"Enter the number of terms to approximate (or zero to quit):"<<endl;
cin>>n;
if(n != 0)
{
double piValue = calculatePI(n+1);
cout<<"The approximation is "<<fixed<<setprecision (3) <<piValue<<" using "<<n<<" terms."<<endl;
}
}while(n!=0); //Repeat till we encounter 0
}
//Sample Output
Enter the number of terms to approximate (or zero to quit):
3
The approximation is 2.895 using 3 terms.
Enter the number of terms to approximate (or zero to quit):
10
The approximation is 3.232 using 10 terms.
Enter the number of terms to approximate (or zero to quit):
50
The approximation is 3.161 using 50 terms.
Enter the number of terms to approximate (or zero to quit):
100
The approximation is 3.151 using 100 terms.
Enter the number of terms to approximate (or zero to quit):
250
The approximation is 3.146 using 250 terms.
Enter the number of terms to approximate (or zero to quit):
100
The approximation is 3.151 using 100 terms.
Enter the number of terms to approximate (or zero to quit):
2000
The approximation is 3.142 using 2000 terms.
Enter the number of terms to approximate (or zero to quit):
0