编程计算π的近似解:π/4 c语言
时间: 2024-05-19 14:13:44 浏览: 140
#include <stdio.h>
#include <math.h>
int main()
{
int n = 1000000; // 迭代次数
double pi = 0.0;
for (int i = 0; i < n; i++)
{
pi += pow(-1, i) / (2 * i + 1);
}
pi *= 4;
printf("pi = %f\n", pi);
return 0;
}
相关问题
C语言编程5、编程计算π的近似解:π/4=1-1/3+1/5-1/7…, 直到|1/n|<10-6 为止。
```
#include <stdio.h>
int main() {
double pi = 0.0;
double term = 1.0;
int n = 1;
while (term >= 1e-6 || term <= -1e-6) {
pi += term;
n += 2;
term = (n % 4 == 1) ? 1.0 / n : -1.0 / n;
}
pi *= 4;
printf("Approximate value of pi: %f\n", pi);
return 0;
}
```
C语言5、编程计算π的近似解:π/4=1-1/3+1/5-1/7…, 直到|1/n|<10-6 为止。
```c
#include <stdio.h>
int main() {
double pi = 0;
int n = 1;
double item = 1.0;
while (item >= 1e-6 || item <= -1e-6) { // 循环直到|1/n|<10^-6
pi += item; // 累加每一项
n += 2; // 计算下一项的分母
item = -item * (n - 2) / n; // 计算下一项的值
}
pi *= 4; // π=4*(π/4)
printf("pi = %lf\n", pi);
return 0;
}
```
阅读全文