-4

I have written a code to calculate this to 100th sentence for pi but it shows "3" this the formula

#include <iostream>
using namespace std;

int main()
{
    int n = 1;
    double a, P = 0;
    for (n; n <= 100; n++) {
        a = 4 / (2 * n - 1);
        if (n % 2 == 0) {
            a = -a;
        }

        P = P + a;
    }

    cout << P;
    system("pause");

    return 0;
}
m reza
  • 9
  • 1
  • 1
    Wild guess - you don't know that [floating point math is broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Fureeish Dec 09 '18 at 21:58
  • 3
    "it does not work" is rarely a useful problem description. You will receive more positive responses if you post your expected and actual results, so that we don't have to guess about what you are expecting to see. – Claies Dec 09 '18 at 22:02
  • 4/3 is 1. 4/5 is 0. 4/7 is 0. 4/9 is 0. 4/11 is 0. 4/13 is 0. What's 3-1+0-0+0-0...? – user253751 Dec 10 '18 at 00:13

1 Answers1

2

4/(2*n-1) is evaluated in integer arithmetic since all the coefficients are integral types. This means that any decimal part is truncated.

4.0 / (2 * n - 1) is one fix.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483