So I tried making a basic pi searcher based on the Gregory-Leibniz series. My problem is it returns 3.0000, and I don't have a clue why...
This is the basic program:
int i = 1, j = 1;
double pi = 0;
for (i; i < 1000; i++)
{
if(i % 2 != 0)
{
pi = pi + (4 / j);
}
else
{
pi = pi - (4 / j);
}
j = j + 2;
}
The 4/j
is entirely integer math, which means it will round down to an integer before being added. Some options are 4.0 / j
and (double)4 / j
.
The MSDN has an article on C floating-point constants that explains the notation you should use to ensure a literal value is treated as a float or a double.