0

I'm trying to approximate pi in a C++ program. I'm new to the language, and am not understanding why my pi variable wont change

The code:

double pi = 1;
for (int i = 0; i <+ k; i++){
    int denominator = (i * 2) + 3;
    if (i % 2 == 0){pi -= (1 / denominator);}
    else{pi += (1 / denominator);}
}
    
pi *= 4;
cout << "Approximation of pi is " << pi << endl;
  • 1
    Explanation of duplicate target: `1` and `denominator` are both `int`s. That means that integer division is performed. It rounds the result to `0` before subtracting it from `pi`. You can cause it to perform floating point division earlier by changing it to `1. / denominator`, using the floating point literal `1.` instead of the integer literal `1`. – Nathan Pierson Sep 23 '22 at 22:09
  • IMHO, I like to use a "sign" variable that switches between +1 and -1 every iteration: `sign = sign * (-1);` You multiply the *term* by the `sign` variable, then add to the sum. This should simplify your code. – Thomas Matthews Sep 23 '22 at 23:29

0 Answers0