topic:
Calculating π / 4 = 1 - 1/3 + 1/5 - 1/7 + ..., until the last one is less than 10-6.
Ideas:
Number Sequence can be expressed as 1 / (2 × i + 1), Observe that, when i is a multiple of 2, that is positive, negative otherwise. Accumulation may be achieved by circulating, after each accumulation is determined whether the condition is satisfied.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double sum = 0.0, term = 0.0;
int i = 0;
do {
term = 1.0 / (i * 2 + 1);
if (i % 2 == 0) {
sum += term;
} else {
sum -= term;
}
++i;
} while (term > 1e-6);
cout << setprecision(6) << fixed << sum << endl;
return 0;
}