我对python相当陌生,试图从while循环中找到最大值,我尝试了制作一个列表,但这似乎不起作用,这是我的代码,欢迎任何帮助
其思想是以用户输入的速度以用户定义的角度发射弹丸,使用运动方程,然后计算并绘制垂直距离和水平距离。到目前为止,曲线图显示了准确的结果,但是当我试图找到最大高度时,它只给出了while循环的最后一个值。我试着做一个列表,从中找出最大值,但它又只给出了最后一个值
import matplotlib.pyplot as plt
import math
print("This programme finds the maximum distance that a projectile travels when fired from ground level at an initial velocity.")
print("")
print("Air resistance is negligible")
u= float(input("Please enter the initial velocity: "))
#print(u)
a = -9.81
xv=0.0
xh=0.0
t=1.0
ang= float(input("Please enter the angle of fire, between 0 and 90 degrees: "))
rad=((math.pi)/(180))*(ang)
uh=(u)*(math.cos(rad))
uv=(u)*(math.sin(rad))
print(rad, uh, uv)
while range (xv>=0):
list=[]
xv = ((uv)*(t))+((0.5)*(a)*(t)*(t))
xh = (uh)*(t)
vv=uv+(a*t)
vh=uh
t=t+1
xv = max(xv)
plt.plot(xh,xv)
plt.scatter(xh, xv)
if xv<=0:
break
print(list)
print("")
print("The maximum height is", max(xv) , "m, with a flight time of", t, "s")
print("")
print("The velocity when the projectile lands is",vv,"m/s" )
plt.xlabel('Horizontal distance (m)')
plt.ylabel('Vertical distance (m)')
plt.show()
您可以在使用循环时预先结束
将下面的行放入循环中
然后使用
max_xv
作为最大值不要使用关键字作为变量名-这里,
list
可以在while循环开始之前初始化高度列表:
然后
append
值作为循环的一部分(除了使用您的结构外,还有其他方法可以实现这一点…)循环完成后,可以使用
max
进行检查综上所述,程序的中间部分可能看起来像:
(我重新排序,改进循环以正确退出,并减少时间增量)
相关问题 更多 >
编程相关推荐