从while循环中查找最大值

2024-04-28 22:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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()

Tags: the用户列表ispltmathuvdistance
2条回答

您可以在使用循环时预先结束

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))

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

相关问题 更多 >