c-exercises/approximate-pi.c

26 lines
516 B
C
Raw Normal View History

2013-05-09 19:18:10 +02:00
#include <stdio.h>
#include <stdbool.h>
double approximate_pi(unsigned int steps) {
double approximate_pi = 4.0;
bool subtract = true;
2013-05-09 19:32:02 +02:00
for (int i = 2; i <= steps; i++) {
2013-05-09 19:18:10 +02:00
if (subtract) {
2013-05-09 19:32:02 +02:00
approximate_pi -= (4.0 / (i * 2 - 1));
2013-05-09 19:18:10 +02:00
} else {
2013-05-09 19:32:02 +02:00
approximate_pi += (4.0 / (i * 2 - 1));
2013-05-09 19:18:10 +02:00
}
subtract = !subtract;
}
return approximate_pi;
}
int main(int argc, char *argv[]) {
// printf("sizeof(int) = %d\n", sizeof(int));
printf("pi = %8.7f\n", approximate_pi(10000000));
2013-05-09 19:20:26 +02:00
return 0;
2013-05-09 19:18:10 +02:00
}