Python 練習例20
問題:1つのボールが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回目以降、着地時の距離は反発高さ×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回目以降、着地時の距離は反発高さ×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} メートルです。)
total_distance = 0
current_height = height
for i in range(1, times + 1):
# 2回目以降、着地時の距離は反発高さ×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 米。その他の拡張