Python 练习实例20

简介: Python 练习实例20

题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

程序分析:

程序源代码:

Python 实例 1

#!/usr/bin/python# -*- coding: UTF-8 -*- tour = []height = [] initial_height = 100.0  # 初始高度num_bounces = 10  # 弹跳次数 for i in range(1, num_bounces + 1):     # 从第二次开始,落地时的距离应该是反弹高度乘以2(弹到最高点再落下)    if i == 1:         tour.append(initial_height)    else:         tour.append(2 * initial_height)         initial_height /= 2    height.append(initial_height) total_distance = sum(tour)final_bounce_height = height[-1] print(f"总高度:tour = {total_distance}")print(f"第{num_bounces}次反弹高度:height = {final_bounce_height}")

以上实例输出结果为:

总高度:tour = 299.609375

第10次反弹高度:height = 0.09765625


实例 2

def calculate_distance_and_height(height, times):

   total_distance = 0

   current_height = height


   for i in range(1, times + 1):

       # 从第二次开始,落地时的距离应该是反弹高度乘以2(弹到最高点再落下)

       if i == 1:

           total_distance += current_height

       else:

           total_distance += current_height * 2  # 每次下落和反弹的距离

       current_height /= 2  # 反弹后的高度


   return total_distance, current_height


# 初始高度为100米,计算第10次落地时的总距离和反弹高度

height = 100

bounce_times = 10

total_distance, final_height = calculate_distance_and_height(height, bounce_times)


print(f"第{bounce_times}次落地时,共经过 {total_distance} 米。")

print(f"第{bounce_times}次反弹的高度为 {final_height} 米。")

以上实例输出结果为:

第10次落地时,共经过 299.609375 米。

第10次反弹的高度为 0.09765625 米。

相关文章
|
19小时前
|
Python
Python 练习实例27
Python 练习实例27
|
19小时前
|
Python
Python 练习实例26
Python 练习实例26
|
19小时前
|
Python
Python 练习实例25
Python 练习实例25
|
1天前
|
Python
Python 练习实例24
Python 练习实例24
|
1天前
|
Python
Python 练习实例22
Python 练习实例22
|
1天前
|
数据安全/隐私保护 Python
经验大分享:python练习:从番号到封面
经验大分享:python练习:从番号到封面
|
1天前
|
数据安全/隐私保护 Python
经验大分享:python练习:从番号到封面
经验大分享:python练习:从番号到封面
|
1天前
|
Python
Python 练习实例23
Python 练习实例23
|
2天前
|
Python
经验大分享:python类函数,实例函数,静态函数
经验大分享:python类函数,实例函数,静态函数