Calculate pi with an infinite series
/* I cannot successfully test while (finalResult <= 3.14) inside the while loop.
My code only allows me to enter random values of i to calculate 3.14159.
Problem statement is below:
Calculate pi from the infinite series:
pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 +... )
Print a table that shows the value of pi approximated by one term of this seris, by two terms, by three terms, etc.
How many terms of the series do you have to use before you first get
3.14, 3.141, 3.1415, and then 3.14159?
-- Thank you for your advise and assistance!
*/
#import <stdio.h>
My code only allows me to enter random values of i to calculate 3.14159.
Problem statement is below:
Calculate pi from the infinite series:
pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 +... )
Print a table that shows the value of pi approximated by one term of this seris, by two terms, by three terms, etc.
How many terms of the series do you have to use before you first get
3.14, 3.141, 3.1415, and then 3.14159?
-- Thank you for your advise and assistance!
*/
#import <stdio.h>
int main (int argc, const char * argv[]) {
// insert code here...
int count = 1, i = 1, cntTester = 0;
float frac, temp;
float sumResult = 0.0, finalResult = 0.0;
while (i < 225000)
{
frac = i;
if(count%2 == 0)
{
temp = -1/frac;
}
else
{
temp = 1/frac;
}
sumResult += temp;
finalResult = 4*sumResult;
i += 2;
count++;
cntTester++;
}
printf(" Result = %.6f", finalResult);
printf(" While loop executed %d times", cntTester);
return 0;
}
MacBook Pro, Mac OS X (10.5.6)