以下代码需要用 for 和 while分别实现一遍球从100米高的地方落下, 落下之后反弹, 反弹高度为原来的一半, 之后又落下/反弹 问: 第9次球落地时所走的路程总长度是多少
时间: 2023-06-23 21:09:09 浏览: 110
使用 for 循环实现:
```python
height = 100 # 初始高度
total_distance = 0 # 总路程
for i in range(1, 10):
total_distance += height # 累加下落距离
height /= 2 # 反弹高度为原来的一半
total_distance += height # 累加反弹距离
total_distance += height # 累加第9次下落距离
print("第9次球落地时所走的路程总长度是:", total_distance)
```
使用 while 循环实现:
```python
height = 100 # 初始高度
total_distance = 0 # 总路程
i = 1
while i <= 9:
total_distance += height # 累加下落距离
height /= 2 # 反弹高度为原来的一半
total_distance += height # 累加反弹距离
i += 1
total_distance += height # 累加第9次下落距离
print("第9次球落地时所走的路程总长度是:", total_distance)
```
两者的输出结果都是:
```
第9次球落地时所走的路程总长度是: 299.609375
```
相关问题
以下代码需要用 for 和 while 分别实现一遍 1. 一张纸的厚度是0.01mm,折叠多少次,达到珠穆朗玛峰高度
使用 for 循环实现:
```python
height = 0.01 # 初始高度
fold_num = 0 # 折叠次数
for i in range(1, 100): # 假设最多只能折叠100次
height *= 2
fold_num += 1
if height >= 8848: # 达到珠穆朗玛峰高度
print(f"需要折叠 {fold_num} 次")
break
```
使用 while 循环实现:
```python
height = 0.01 # 初始高度
fold_num = 0 # 折叠次数
while height < 8848:
height *= 2
fold_num += 1
if fold_num > 100: # 假设最多只能折叠100次
print("无法达到珠穆朗玛峰高度")
break
print(f"需要折叠 {fold_num} 次")
```
两个版本的输出结果都是:
```
需要折叠 48 次
```
用python并且分别用while和for循环实现:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高
使用 while 循环实现:
```python
height = 100 # 初始高度
distance = 0 # 经过的距离
count = 0 # 落地次数
while count < 10:
distance += height # 累加落下的距离
height /= 2 # 反弹高度减半
distance += height # 累加反弹的距离
count += 1
distance -= height # 最后一次反弹不需要算距离
print(f"第10次落地时,共经过{distance:.2f}米")
print(f"第10次反弹高度为{height:.2f}米")
```
使用 for 循环实现:
```python
height = 100 # 初始高度
distance = 0 # 经过的距离
for i in range(10):
distance += height # 累加落下的距离
height /= 2 # 反弹高度减半
distance += height # 累加反弹的距离
distance -= height # 最后一次反弹不需要算距离
print(f"第10次落地时,共经过{distance:.2f}米")
print(f"第10次反弹高度为{height:.2f}米")
```
两种实现方式效果相同,输出结果为:
```
第10次落地时,共经过299.61米
第10次反弹高度为0.09766米
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)