To calculate Pi you can use the equation pi/4=1-(1/3)+(1/5)-(1/7)+... Multiply it by 4 and you get Pi I created a formula to calculate each step of the equation relative to its position 1/(2n-1) and wrote code for it
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
double p = 0;
double pi = 0;
int j = 1;
do
{
if (j % 2 == 1)
{
p = p + (1 / (2 * j - 1));
}
else
{
p = p - (1 / (2 * j - 1));
}
pi = p * 4;
printf("%lf\n", pi);
j++;
} while (j < 10);
return (EXIT_SUCCESS);
}
but it is only putting out 4.0000
Why? I cant find the mistake I made.
In the statement p = p + (1 / (2 * j - 1));
expression (1 / (2 * j - 1)
yields in integer. To get expected result make either operand as floating type i.e either 1.0
or (float)(2 * j - 1)
Replace the statement
p = p + (1 / (2 * j - 1));/* 1/(2*j-1) results in integer, you won't get expected result */
with
p = p + (1. / (2 * j - 1));/* 1. means making floating type */