Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Calculating Pi

Name: Jim Profit 2013-02-13 0:11

Alright, for the life of me, I can't figure out what is wrong with my code. I'm trying to use this formula to calculate pi in c++. I've tried it with a while loop too, but it always gives me pi = 1. Can anyone help me out?

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
    char reply;

    double pi=0;
    long n;
    long i;

    cout << "Enter the value of n: ";
    cin >> n;
   
    // Set the state of the output stream to format using 2 places of decimals.
    cout << setprecision(4);
    cout << fixed << setprecision(2);// Set the output stream to display floating point numbers in fixed point notation


for (i = 0; i <= n; i++) {
    if (i%2 == 0)
        pi = (pi+(1 / (2 * i + 1)));
    else
        pi = pi-(1 / (2 * i + 1));
    cout << pi << endl;
}
pi = pi * 4;
cout << pi;

// "Pause" so the user can see the results

    cout << "\nEnter q to quit... ";
    cin >> reply;
return 0;

}

Name: Anonymous 2013-02-13 14:36

I ran your program. It only displayed:
[tt]
kill me
kill me
kill me
please kill me
[/tt]

Name: you can fix this 2013-02-15 8:35

when declaring pi, because it's a double use "0.0" instead of plain 0 (which is an int). This could be why your answer was an integer instead of your prefered double.

Name: Anonymous 2013-02-15 22:14

#include <stdio.h>
#define pi 3.141592

int main()
{
printf("%f\n", pi);
}

no thanks please

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List