我正试图让这段代码正常工作,但我一直收到错误:
h0,time = getInputs() NameError:名称'getInputs‘未定义“未定义”。
有人能帮我弄清楚为什么会发生这种事吗?
from math import sin, cos, radians
class Projectile:
def __init__(self, angle, velocity, height):
"""Create a projectile with given launch angle, initial
velocity and height."""
self.xpos = 0.0
self.ypos = height
theta = radians(angle)
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
self.maxypos = max(self.maxypos, self.ypos)
def update(self, time):
"""Update the state of this projectile to move it time seconds
farther into its flight"""
self.xpos = self.xpos + time * self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
self.yvel = yvel1
def getY(self):
"Returns the y position (height) of this projectile."
return self.ypos
def getX(self):
"Returns the x position (distance) of this projectile."
return self.xpos
def getInputs():
a = eval(input("Enter the launch angle (in degrees): "))
v = eval(input("Enter the initial velocity (in meters/sec): "))
h = eval(input("Enter the initial height (in meters): "))
t = eval(input("Enter the time interval between position calculations: "))
return a,v,h,t
def main():
angle, vel, h0, time = getInputs()
cball = Projectile(angle, vel, h0)
while cball.getY() >= 0:
cball.update(time)
print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))
if __name__ == "__main__":
main()发布于 2017-11-04 00:38:27
getInputs的缩进为off (它放在类中):
(请注意,在用户输入上使用eval是一个非常糟糕的主意)
from math import sin, cos, radians
class Projectile:
def __init__(self, angle, velocity, height):
"""Create a projectile with given launch angle, initial
velocity and height."""
self.xpos = 0.0
self.maxypos = self.ypos = height # defining self.maxypos
theta = radians(angle)
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
self.maxypos = max(self.maxypos, self.ypos)
def update(self, time):
"""Update the state of this projectile to move it time seconds
farther into its flight"""
self.xpos = self.xpos + time * self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
self.yvel = yvel1
def getY(self):
"Returns the y position (height) of this projectile."
return self.ypos
def getX(self):
"Returns the x position (distance) of this projectile."
return self.xpos
def getInputs():
a = eval(input("Enter the launch angle (in degrees): "))
v = eval(input("Enter the initial velocity (in meters/sec): "))
h = eval(input("Enter the initial height (in meters): "))
t = eval(input("Enter the time interval between position calculations: "))
return a,v,h,t
def main():
angle, vel, h0, time = getInputs()
cball = Projectile(angle, vel, h0)
while cball.getY() >= 0:
cball.update(time)
print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))
if __name__ == "__main__":
main()修正了@PM2Ring所指出的self.maxypos声明
https://stackoverflow.com/questions/47106158
复制相似问题