用c语言,用3种循环分别计算圆周率
时间: 2024-01-26 20:47:15 浏览: 180
1. for循环计算圆周率
```c
#include <stdio.h>
int main() {
int n = 1000000; // 迭代次数
double pi = 0.0;
double sign = 1.0;
for (int i = 1; i <= n; i++) {
pi += sign / (2 * i - 1);
sign = -sign;
}
pi *= 4;
printf("pi = %f\n", pi);
return 0;
}
```
2. while循环计算圆周率
```c
#include <stdio.h>
int main() {
int n = 1000000; // 迭代次数
double pi = 0.0;
double sign = 1.0;
int i = 1;
while (i <= n) {
pi += sign / (2 * i - 1);
sign = -sign;
i++;
}
pi *= 4;
printf("pi = %f\n", pi);
return 0;
}
```
3. do-while循环计算圆周率
```c
#include <stdio.h>
int main() {
int n = 1000000; // 迭代次数
double pi = 0.0;
double sign = 1.0;
int i = 1;
do {
pi += sign / (2 * i - 1);
sign = -sign;
i++;
} while (i <= n);
pi *= 4;
printf("pi = %f\n", pi);
return 0;
}
```
阅读全文