Yêu cầu:
Tính PI với sai số 0.0001 theo công thức: PI/4 = 1 – 1/3 + 1/5 – 1/7 +…
Thuật toán:
– Dùng vòng lặp for().
– PI/4 = ∑(1 + ((-1)n/(2n+1)))
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/************************************************************ #include "stdio.h" #include "conio.h" #include "math.h" #define E 0.0001 void main() { float S = 0; float e = 1; // sai so e = 1/(2n + 1) int n = 0; while(e > E) { e = (float)1/(2*n + 1); if(n%2 == 0) S = S + e; else S = S - e; n++; } printf("\n PI = %f", 4*S); getch(); } |
Kết quả:
1 |
PI = 3.141797 |
Leave a Reply