Exercise #3: Calculate the value of Pi Write a C++ program that calculates an es
ID: 3909273 • Letter: E
Question
Exercise #3: Calculate the value of Pi Write a C++ program that calculates an estimate of the value of Pi. In mathematics, Pi is approximated by the following formula: Pi-4-4/3 + 4/5-4/7 + 4/9-4/11 +4/13 . 4/15 +4/17 The more terms you use, the closer to Pi you get (The above equation shows 9 terms). For example, if you use 5 terms to calculate Pi, your formula would be as follows: Pis 4-4/3 + 4/5-4/7 + 4/9 4-1.333333333333 + 0.8-0.571428 + 0.4444444-3.33968254. Write a program that prompts the user to enter the number of terms which will be used to calculate Pi. Also, your program should keep asking the user to re-calculate PI as long as you wish. Your program should get as close as it can to Pi- 3.141592653589793 Sample input/output: Enter number of terms for Pi calculation: 5 Your results are: Actual Calculated Pi 3.339682540 Would you like to try another Pi calculation? (y/n): Y Pi -3.141592653589793 Enter number of terms for Pi calculation: 580000 Your results are: Actual Calculated Pi -3.141590654 Would you like to try another Pi calculation? (y/n): y Pi 3.141592653589793 Enter number of terms for Pi calculation: 5ee00000 Your results are: Actual Calculated Pi -3.141592634 Would you like to try another Pi calculation? (y/n):n Pi -3.141592653589793 I am satisfied with this result. Note: Your results might be just a little different from the above as far as the precision.Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n ;
char ch = 'y';
double result = 0;
while(ch=='y'||ch=='Y') {
result = 0;
cout << "Enter the number of terms for PI calculations:" << endl;
cin >> n;
for(int i=0, j=1; i<n; i++, j+=2){
if(i%2 == 0)
result = result + (1/(double)j);
else
result = result - (1/(double)j);
}
result = 4 * result;
cout<<"Your results are: "<<endl;
cout<<"Actual Pi:"<<M_PI<<endl;
cout<<"Calculated Pi:"<<result<<endl;
cout<<"Would you like to try another Pi calculation? (y/n):"<<endl;
cin >> ch;
}
cout<<"I am satisifed with this result"<<endl;
return 0;
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.