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

基于用户输入的抛体运动轨迹绘制代码问题求解

抛体运动轨迹代码修复说明

核心错误原因:你通过input()获取的theta(抛射角)和t(时间参数)都是单个数值,不属于可迭代的序列类型,无法直接放在for循环中做遍历对象,除此之外代码还存在其他可运行性问题,逐一修复如下:

  • 补全numpy库导入,原代码调用np.cos、np.sin但未导入numpy会触发二次报错
  • numpy内置三角函数接收弧度值,输入的角度需要先转换为弧度再参与计算,否则结果会完全偏离预期
  • 不需要遍历单个抛射角,直接生成连续的时间序列,即可计算每个时间点对应的x、y坐标完成轨迹绘制
  • 可优化为自动计算抛体最大飞行时间,不需要手动输入时间参数,避免轨迹绘制不全

修复后可运行代码

import numpy as np
import matplotlib.pyplot as plt

print("Xt = V0 * (cos(Θ)) * t") # 修正原公式多余括号
print("Yt = Y0 + (V0 * t * sin(Θ)) - (0.5 * g * t²)")
g = 9.8
v = float(input("请输入初速度(单位:m/s):"))
theta_deg = int(input("请输入抛射角(单位:度):"))
# 角度转弧度
theta_rad = np.deg2rad(theta_deg)
# 自动计算最大飞行时间,不需要手动输入时间
t_total = 2 * v * np.sin(theta_rad) / g
# 生成连续时间序列,步长0.01s保证轨迹平滑
t_seq = np.arange(0, t_total, 0.01)

# 批量计算所有时间点的坐标
x1 = v * t_seq * np.cos(theta_rad)
y1 = v * t_seq * np.sin(theta_rad) - 0.5 * g * (t_seq ** 2)

plt.plot(x1, y1)
plt.xlabel("水平位移(m)")
plt.ylabel("竖直高度(m)")
plt.title(f"抛体运动轨迹(初速度{v}m/s,抛射角{theta_deg}°)")
plt.show()

如果需要保留手动输入最大时间的逻辑,只需要把自动计算t_total的逻辑替换为如下代码即可:

t_total = float(input("请输入最大计算时间(单位:s):"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:57:04