从while循环中查找最大值



我对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 = 0

将以下线路放入环路

max_xv = max(max_xv, xv)

然后使用max_xv作为最大值

不要使用关键字作为变量名-这里是list

您可以在while循环开始前初始化高度列表:

heights = []

然后append值(还有其他方法可以做到这一点,但使用您的结构…(

heights.append(xv)

循环结束后,您可以使用max进行检查

print( max(heights))

把这些放在一起,你的程序中间可能看起来像:

print(rad, uh, uv)
heights = []
t = 0.0
while xv >= 0:
# plot this point
plt.plot(xh,xv)
plt.scatter(xh, xv)
# save height
heights.append(xv)
# calculate next point
t += 0.1
xv = uv*t + 0.5*a*t*t
xh = uh*t
vv = uv + a*t
vh = uh
# xv has gone negative so loop has finished
print (max(heights))

(我重新排序,改进了循环以正确退出,并减少了时间增量(

最新更新