"""
高空抛物
一球从100米高度自由落下,每次落地后反跳回原高度的一半,再落下。
求它在第10次落地时,共经过多少米?第10次反弹多高?
"""
def calculate(height, times):
"""
计算经过的总距离和最后一次反弹的高度。
参数:
height -- 起始高度
times -- 反弹次数
返回值:
distance -- 经过的总距离
final_height -- 最后一次反弹的高度
"""
distance = 0 # 初始化经过的总距离
current_height = height # 初始化当前高度为起始高度
# 循环计算每次落地和反弹的距离
for i in range(1, times + 1):
# 第一次落地特殊处理,之后每次落地反弹的距离都是前一次的2倍
if i == 1:
distance += current_height
else:
distance += current_height * 2
current_height /= 2 # 每次落地后,高度减半
return distance, current_height
# 设置起始高度和反弹次数
h = 100
t = 10
# 调用函数计算最终结果
final_distance, final_height = calculate(h, t)
# 打印结果
print(f"第{t}次落地时,共经过{final_distance}米")
print(f"第{t}次反弹{final_height}米")
评论前必须登录!
注册