0

I am new to c++. I have come from c# and am quite good at it. This is puzzling me though. I am trying to write a basic script to calculate pi using the Leibniz formula. I know it isn't that effective, it's just to try and get used to the language. The problem is, I first define my variable's value to one, then use a for loop to iterate through the various steps. When I use cout << pi << endl; however, it outputs one, as if my for loop never ran. It also outputs it very quickly, also as though the loop never ran. Here's the code. I tried doing it in the main function, but that didn't work so I did it in a separate function, hoping that would work. It still didn't. Any help would be appreciated.

#include <iostream>
using namespace std;
double calcpi() {
    double pi;
    pi = 1;
    for (int i = 3; i < 1000000; i += 2) {
        if (((i - 1) % 4) != 0) {
            pi -= 1 / i;
        }
        else {
            pi += 1 / i;
        }
    }
    return pi;
}
int main()
{
    cout << calcpi() << endl;
    return 0;
}

0 Answers0