I have a program written where I can approximate pi with an n value entered.The
ID: 3544016 • Letter: I
Question
I have a program written where I can approximate pi with an n value entered.The outputs need to look like either: (not computable due to negative):
This program approximates pi using an n-term series expansion.
Enter the value of n> -3
-3 is an invalid number of terms
or:(all positive numbers):
This program approximates pi using an n-term series expansion.
Enter the value of n> 6
pi[6] = 4[1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11] = 2.97604617604617560644
Here is the program I have so far. I am lost as to what to do to this to get it to work:
11#include<iostream>
12#include<cmath>
13
14using namespace std;
15
16
17
18void compute_pi(const int PRECISION)
19{
20double pi =4.0;
21
22for(int =0; i< PRECISION ++i)
23{
24pi += (i%2 == 0 ? -4.0: 4.0)/(3.0+i*2);
25}
26return(pi);
27}
28
29int main()
30{
31double i;
32
33cout<<"This program approximates pi using an n-term series expression."<<endl;
34cout <<"Enter the value of n>" << endl;
35cin >> i;
36
37compute_pi();
38
39cout <<"pi["<<i<<"] = 4["<<i<<"] = "<< pi << endl;
40
41return 0;
42}
I am getting there errors in the code:
14: error: expected nested-name-specifier before
Explanation / Answer
#include<iostream>
#include<cmath>
using namespace std;
double compute_pi(const int PRECISION)
{
double pi = 4.0;
for(int i=1; i< PRECISION; ++i)
{
pi += (i%2 == 1 ? -4.0: 4.0)/(1.0+i*2);
}
return pi;
}
int main()
{
int n;
cout<<"This program approximates pi using an n-term series expression."<<endl;
cout <<"Enter the value of n>" << endl;
cin >> n;
if (n <= 0)
cout << n << " is an invalid number of terms" << endl;
else
{
cout <<"pi["<<n<<"] = 4[1";
for (int i = 1; i < n; ++i)
cout << (i%2 ? " - 1/" : " + 1/") << 2*i+1;
cout<<"] = ";
cout.precision(21);
cout << compute_pi(n) << endl;
}
return 0;
}
//sample run: http://ideone.com/mBLN84
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.