Sunday, August 2, 2009

C++ Approximation of Pi?

I'm supposed to write a program that approximates the value of pi using the series 4[1-1/3+1/5-1/7+1/9...] The program takes an input value n that determines the number of terms in the approximation and outputs this approximation. I can figure out most of the program, except for how to loop the approximation series...here's what I have so far:


#include %26lt;iostream%26gt;


using namespace std;





int main()


{





int digits, n(0), pi(4);


double total, x(3);





cout%26lt;%26lt;"Please input the number of approximations you would like to see:"%26lt;%26lt;endl;


cin%26gt;%26gt;digits;





while(digits%26gt;n)


{


total=-1./x+1./(x+2.);


//cout%26lt;%26lt;total;


x=x+4;


n=n+1;


}


total=4*(total+1);


cout%26lt;%26lt;total%26lt;%26lt;endl;





system("pause");





return 0;


}

C++ Approximation of Pi?
cout%26lt;%26lt;"Please input the number of approximations you would like to see:"%26lt;%26lt;endl;


cin%26gt;%26gt;maxTerms;





total = 0.0;


int sign = 1;


for (int term = 0; term != maxTerms; ++term)


{


total += sign * (1.0/(1 + term * 2));


sign *= -1;


}


total=4*(total+1);
Reply:Try this:


http://www.codeproject.com/KB/recipes/CR...

secret garden

No comments:

Post a Comment