我正在学习工程概念中的运动方程,下面是我正在学习的方程:

为了完成这一课,我被告知要创建一个Python程序,该程序输出弹丸的水平速度和最大高度。这是我的节目:
# x = v_x * t + x_0
# y = 0.5(g * (t**2)) + v_y0 * t + y_0
# v_y = v_y0 + g* t
# v_y ** 2 = 2*g*y + v_y0 ** 2
# Input is time, x-range, launch angle, starting coordindates of launch (defined as 0,0)
time = float(raw_input("What was the time in seconds: "))
x_range = float(raw_input("How far was the projectile launched horizontally in feet: "))
launch_angle = float(raw_input("What was the launch angle in degrees: "))
x_o, y_o = 0, 0
gravity = -32.2
v_y = 0
# Horizontal velocity in mph
v_x = ((x_range - x_o)/time * 3600)/5280
print "\nThe horizontal velocity is {0:} miles per hour".format(v_x)
# Maximum height in feet
vy = 0
v_yo = vy - gravity * (time/2)
height = 0.5 * (gravity * ((time/2) ** 2)) + (v_yo * (time/2)) + 0
print "The maximum height is {0:} feet".format(height)我目前的问题是:
目前,发射角度不影响结果,只是因为规格。示例输出:
What was the time in seconds: 1.2
How far was the projectile launched horizontally in feet: 3
What was the launch angle in degrees: 45
The horizontal velocity is 1.70454545455 miles per hour
The maximum height is 5.796 feet发布于 2017-01-17 17:26:15
我将改进以下几点:
3600和5280可能对您或现在对您来说是明确的,但在未来的某个人中可能不适合您。或者,在这种情况下,最好有一个通用的convert_to_mph()函数。v_y和vy下了两次定义--我想你是想这么做一次y_o变量print()函数和not语句(为了实现Python2和3的兼容性)改进版本:
X_O = 0
GRAVITY = -32.2
V_Y = 0
def convert_to_mph(value):
"""Converts velocity from m/s to mph. TODO: what formula used?"""
return value * 3600 / 5280
# Input is time, x-range, launch angle, starting coordinates of launch (defined as 0,0)
time = float(raw_input("What was the time in seconds: "))
x_range = float(raw_input("How far was the projectile launched horizontally in feet: "))
launch_angle = float(raw_input("What was the launch angle in degrees: "))
# Horizontal velocity
v_x = (x_range - X_O) / time
v_x_mph = convert_to_mph(v_x)
print("\nThe horizontal velocity is {0:} miles per hour".format(v_x_mph))
# Maximum height
v_yo = V_Y - GRAVITY * (time / 2)
height = 0.5 * (GRAVITY * ((time / 2) ** 2)) + (v_yo * (time / 2)) + 0
print("The maximum height is {0:} feet".format(height))您可以通过引入单独的计算水平速度和最大高度的函数来进一步改进代码。如果这样做,代码块之前的注释将自然转换为函数docstring(您需要改进它,添加更多关于如何计算结果值的信息),从而使代码更像奏鸣曲。
另外,表到脚的转换也应该通过一个单独的通用函数来完成,比如速度的convert_to_mph。
另外,顺便指出,从可用性的角度来看,用户输入值没有验证。
您还可以使用Python2和3兼容的获取用户输入的方法:
try:
input = raw_input
except NameError:
pass
time = float(input("What was the time in seconds: "))
x_range = float(input("How far was the projectile launched horizontally in feet: "))
launch_angle = float(input("What was the launch angle in degrees: "))但这将取决于兼容性在这一点上对你有多重要。
https://codereview.stackexchange.com/questions/152877
复制相似问题