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

Slingshot算法Python代码异常:while循环后无输出求助

问题分析与修复方案

核心死循环原因

  • 你的while Projectile_CS >= 0:循环里,只执行了tx += 0.1,但从未更新Projectile_CS的值。初始时tx=0,Projectile_CS计算为0,循环条件一直成立,程序陷入死循环,自然没有后续输出。
  • 另外,竖直位移的物理公式完全错误:正确的抛体竖直位移公式是 y = v_y * t - 0.5 * g * t²,你写成了(vy * tx) - (-g*tx*tx),等价于vy*tx + g*tx²,这个值会随着tx增大一直递增,永远不会小于0,进一步加剧了死循环。

其他物理公式错误

  • 最大高度计算错误:正确的最大高度应该是(vy ** 2) / (2 * g),或者用到达最高点的时间t_top = vy / g代入位移公式计算。你用t = vy/8完全没有物理依据。
  • 总飞行时间计算错误:抛体落地的总时间应该是2 * vy / g(当起始和落地高度相同时),你的代码里没有正确计算,而是用死循环的tx来代替,逻辑错误。

修复后的完整代码

from math import sin, cos, radians

def Sling():
    # 输入速度和角度,注意角度要转成弧度(math的sin/cos用弧度计算)
    b_h = float(input("Input starting speed:   "))
    b_angl_deg = float(input("Input starting angle (degrees):   "))
    b_angl = radians(b_angl_deg)  # 转弧度
    
    vy = b_h * sin(b_angl)
    vx = b_h * cos(b_angl)
    g = 9.8
    
    # 计算最大高度和总飞行时间
    t_top = vy / g  # 到达最高点的时间
    Max_height = (vy ** 2) / (2 * g)  # 最大高度
    total_time = 2 * vy / g  # 落地总时间(起始高度=落地高度)
    Max_distance = vx * total_time  # 最大水平距离
    
    # 模拟抛体运动过程(可选,用于验证)
    tx = 0
    while tx <= total_time:
        current_y = vy * tx - 0.5 * g * tx ** 2
        print(f"Time: {tx:.1f}s, Height: {current_y:.1f}m")
        tx += 0.1
    
    # 输出结果和可视化
    print("\nDone")
    print("Max Height Visualization:")
    for _ in range(round(Max_height / 5)):
        print("    *")
    print(f"0 {'_' * round(Max_distance / 5)}")
    
    print(f"\nThe maximum height is: {round(Max_height)}m")
    print(f"Max distance is: {round(Max_distance)}m")

Sling()

关键修改说明

  1. 修复死循环:在循环内重新计算current_y(原Projectile_CS),并改用总飞行时间作为循环终止条件(更高效,避免死循环)。
  2. 修正物理公式:使用正确的竖直位移、最大高度、总飞行时间公式。
  3. 角度转弧度:math.sin/cos接受弧度值,所以将输入的角度(默认用户输入的是角度)转成弧度,避免计算错误。
  4. 优化可视化:调整星号的缩进,让高度可视化更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:30:24