I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » C/C++ »

Approx pi c++

tpoole00\′s Photo
21 Nov 11, 2:47PM
(4 replies)
Approx pi c++
I am suppose to approximate pi using this formula

pi = sqrt( 6*(1 + 1/4 + 1/9 + 1/16 + 1/25 +.......) )

so far I have:

#include <iostream>
#include <conio.h>
#include <math.h>
 
using namespace std;
 
int main ()
{
 
double x;
long double pi;
double i;
cout << " To how many terms? ";
cin >> i;
 
for (long int n = 1; n <= i; n++) 
{ 
x += n/pow(i,2.0);
n++;
} 
pi =sqrt(6*(1+x));
cout << " Estimated PI value to " << i << " terms: "<< pi; 
cin >> pi;
 
getch();
}
the program runs and everything, but i think my formula written is wrong and i don't how to correct it or if when naming my ints if i used double and long double where i needed to or if i should use int or something else
CodeCogs\′s Photo
23 Nov 11, 5:56PM
You've made a couple of errors:

When you declare "double x" you should really also assign it to zero, i.e.
long double x=0;

In the loop, your code is all wrong, try:
for (int n = 2; n <= i; n++) 
{ 
  x += 1/pow(n,2.0);
}
pi =sqrt(6*(1+x));

You'l notice you don't need n=1, because you've included this result explicitly in the last line above. You don't need to use long int, the int will be easily sufficient for anything you need. If you're going to use a long double for pi, then you should use the same for x.

Hope this helps.
jamess86607\′s Photo
19 Sep 13, 1:39PM
hello everyone welcome to this forum.Here u find all your questions and get your answers. right now i am unable to find your answer.If you want to see c programming you can go through this. --------- [url=http://www.javatutorials.tk] C Programming [/url]
jamess86607\′s Photo
19 Sep 13, 1:40PM
hello everyone welcome to this forum.Here u find all your questions and get your answers. right now i am unable to find your answer.If you want to see c programming you can go through this. --------- http://www.javatutorials.tk
jamess86607\′s Photo
19 Sep 13, 1:40PM
hello everyone welcome to this forum.Here u find all your questions and get your answers. right now i am unable to find your answer.If you want to see c programming you can go through this. --------- www.javatutorials.tk
Currently you need to be logged in to leave a message.