Reputation: 96810
I'm trying to simulate the approximation of pi to 5 decimal places. This is the formula off of which I'm basing it:
But instead of using infinity, I'm approximating it to 5 decimals. This is the code I have, but the result I get is 0. My speculation is because of the integer division, but I've tried adding 0. to one of the dividens but it doesn't help:
#include <cmath>
#include <iostream>
int main() {
int sum = 0;
for (int k = 0; k < 5; ++k) {
sum += pow(-1, k) / (2 * k + 1);
}
sum *= 4;
std::cout << sum;
}
This part:
sum += pow(-1, k) / (2 * k + 1);
I tried changing to:
sum += ( pow(-1, k) + 0. ) / (2 * k + 1);
or
sum += ( pow(-1, k) * 1. ) / (2 * k + 1);
But the result is still 0. What could I be doing wrong?
Upvotes: 1
Views: 189