Search code examples
c++pi

Trying to calculate Pi using a for loop only gives 3


#include <iostream>
#include <iomanip>

using namespace std;

int main() {
float pi =0;
bool add = true;
for (int i =1; i < 30000; i+=2) {
    if (add) {
        pi = pi + (4/i);
        add = false;
    } else {
        pi = pi - (4 / i);
        add = true;

    }
}
cout << setprecision(18);
cout << pi;
return 0;
}

However the output i just 3! All the time.... Why so? What's wrong in my logic?

Is it some wrong in the code or just the Leibniz Series is not on good terms with computers?


Solution

  • pi = pi + (4/i);
    

    Please write pi = pi + 4.0 / i; instead. Integer divided by integer is integer division which won't yield floating point result.