Example 5-7 Find the approximate value of pi
Title description
Use the following formula:
find the approximate value of PI until the absolute value of a certain term is found to be less than 10-6 (the term is not accumulated).
The total width of the required output is 10 digits, and the decimal part is 8 digits.
When using floating-point data in the program, please define it as a double-precision double type.
If you need to calculate the absolute value, you can use the function fabs provided by the C language math library. For example, to find the absolute value of x, it is fabs(x).
Input
no
output
PI=approximate value of pi
The total width of the output is 10 digits, among which decimal Part is 8 bits.
Line feed is output at the end.
Sample input Copy
No
sample output Copy
PI=3.14159065
#include <stdio.h>
#include <math.h>
int main(void) {
int flag = -1;
double term = 1;
double pi = 1;
while (1) {
term += 2;
if (1 / term < pow(10, -6)) break;
pi += flag * 1 / term;
flag = -flag;
}
printf("PI=%10.8f", 4 * pi);
return 0;
}