3种循环分别计算 1+1/2+1/3+1/4+…+1/100
时间: 2023-09-06 10:14:55 浏览: 166
1. for循环:
```python
result = 0
for i in range(1, 101):
result += 1/i
print(result)
```
2. while循环:
```python
result = 0
i = 1
while i <= 100:
result += 1/i
i += 1
print(result)
```
3. do-while循环:
```python
result = 0
i = 1
while True:
result += 1/i
i += 1
if i > 100:
break
print(result)
```
其中,第三种方式模拟了do-while循环,即先执行一次循环体后再判断循环条件。在Python中并没有do-while循环,因此需要通过while True和break语句来实现。
相关问题
c语言用3种循环分别计算 1+1/2+1/3+1/4+…+1/100的结果
1. for循环:
```c
#include <stdio.h>
int main() {
double sum = 0;
for (int i = 1; i <= 100; i++) {
sum += 1.0 / i;
}
printf("sum = %lf\n", sum);
return 0;
}
```
2. while循环:
```c
#include <stdio.h>
int main() {
double sum = 0;
int i = 1;
while (i <= 100) {
sum += 1.0 / i;
i++;
}
printf("sum = %lf\n", sum);
return 0;
}
```
3. do-while循环:
```c
#include <stdio.h>
int main() {
double sum = 0;
int i = 1;
do {
sum += 1.0 / i;
i++;
} while (i <= 100);
printf("sum = %lf\n", sum);
return 0;
}
```
用c语言,用3种循环分别计算 1+1/2+1/3+1/4+…+1/100。
1. for循环:
```c
#include <stdio.h>
int main() {
double sum = 0;
for (int i = 1; i <= 100; i++) {
sum += 1.0 / i;
}
printf("sum = %f", sum);
return 0;
}
```
2. while循环:
```c
#include <stdio.h>
int main() {
double sum = 0;
int i = 1;
while (i <= 100) {
sum += 1.0 / i;
i++;
}
printf("sum = %f", sum);
return 0;
}
```
3. do-while循环:
```c
#include <stdio.h>
int main() {
double sum = 0;
int i = 1;
do {
sum += 1.0 / i;
i++;
} while (i <= 100);
printf("sum = %f", sum);
return 0;
}
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)