You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现小球弹跳总距离计算程序的循环逻辑?

小球弹跳总距离计算问题

问题背景

一项标准的科学实验是让小球自由下落并观察其弹跳高度。确定小球的“弹性”后,该比值即为弹跳系数。例如:

  • 小球从10米高度落下后弹起6米,其弹跳系数为0.6,首次弹跳后总行驶距离为16米;
  • 若继续弹跳,两次弹跳后的总距离为10米+6米+6米+3.6米=25.6米。

注意:每次后续弹跳的行驶距离包括下落至地面的距离加上弹起高度(即下落距离乘以弹跳系数)。

需求

编写一个程序,允许用户输入小球初始高度、允许弹跳次数、弹跳系数,输出小球的总行驶距离。

用户现有代码

def Bounce_Calculator():

    initialHeight = float(input( "What is the initial height? "))
    bouncesAllowed = float(input( "What is the amount of bounces allowed: "))
    bounceIndex = float(input("What is the bounce index : "))
    
    n=0
    while n <= bouncesAllowed :

        newHeight = float(initialHeight*bounceIndex)

        heightDifference = initialHeight-newHeight

        bounceSum = (newHeight/1-bounceIndex)
        totalDistance = ((((2*bounceSum) + initialHeight )))

        print ("The total distance is : ", totalDistance)

        n=bouncesAllowed + 1

Bounce_Calculator()

用户问题

请问该如何编写正确的循环来实现需求?


问题分析与修正方案

现有代码的核心问题

  1. 循环完全失效:你写的while循环仅执行一次,因为直接将n赋值为bouncesAllowed + 1强制跳出循环,根本没实现多次弹跳的累加逻辑。
  2. 数学公式错误:bounceSum = (newHeight/1-bounceIndex)存在运算优先级问题(正确应为newHeight / (1 - bounceIndex)),且该公式是无限弹跳的总距离,不符合“指定弹跳次数”的限制。
  3. 高度未更新:每次计算都用初始高度,没有将当前弹起高度作为下一次下落的高度,导致所有弹跳的高度计算错误。

正确的循环实现逻辑

总距离的计算规则:

  • 第一步:总距离先计入初始下落的高度;
  • 每一次弹跳:弹起高度 = 当前高度 × 弹跳系数,总距离加上该弹起高度的2倍(弹起+再次下落的距离);
  • 终止条件:完成指定次数的弹跳后停止循环。

修正后的代码

def Bounce_Calculator():
    # 输入处理:弹跳次数是计数,转整数更合理
    initial_height = float(input("What is the initial height? "))
    bounces_allowed = int(input("What is the amount of bounces allowed: "))
    bounce_coefficient = float(input("What is the bounce coefficient : "))

    total_distance = initial_height  # 先加初始下落的距离
    current_height = initial_height

    # 用for循环遍历指定弹跳次数
    for _ in range(bounces_allowed):
        current_height *= bounce_coefficient  # 更新为本次弹起的高度
        total_distance += 2 * current_height  # 累加弹起+下落的距离

    # 格式化输出,保留两位小数更直观
    print(f"The total distance is : {total_distance:.2f}")

Bounce_Calculator()

代码说明

  1. 输入优化:将弹跳次数转为整数,符合实际计数场景;
  2. 变量初始化:total_distance初始值为初始下落高度,current_height跟踪当前的弹跳高度;
  3. 循环逻辑:用for循环精准控制弹跳次数,每次循环更新当前高度并累加对应距离;
  4. 输出格式化:用:.2f保留两位小数,结果更清晰。

测试验证

输入:

What is the initial height? 10
What is the amount of bounces allowed: 2
What is the bounce coefficient : 0.6

输出:

The total distance is : 25.60

与题目示例结果完全一致。


内容的提问来源于stack exchange,提问作者SlavNevsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:25:38