2014-06-18 37 views
0

我正在學習如何使用書中的方法,並且在此練習中,我正在試圖找出彈丸的最大高度。我很確定我把等式寫入projectile.py,但每次執行Exercise 1.py時,我從cball.getMaxY()獲得的結果總是"-0.0 meters."我可能錯過了哪些簡單的事情?我在這種方法工作流程中缺少什麼?

# projectile.py 

"""projectile.py 
Provides a simple class for modeling the 
flight of projectiles.""" 

from math import sin, cos, radians 

class Projectile: 

    """Simulates the flight of simple projectiles near the earth's 
    surface, ignoring wind resistance. Tracking is done in two 
    dimensions, height (y) and distance (x).""" 

    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) 

     #Find time to reach projectile's maximum height 
     self.th = self.yvel/9.8 

    def update(self, time): 
     """Update the state of this projectile to move it time seconds 
     farther into its flight""" 
     #Find max height 
     self.maxypos = self.yvel - (9.8 * self.th) 

     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 getMaxY(self): 
     "Returns the maximum height of the projectile." 
     return self.maxypos 

# Exercise 1.py 
from projectile import Projectile 

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())) 
    print("\nMaximum height traveled: {0:0.1f} meters.".format(cball.getMaxY())) 

if __name__ == "__main__": 
    main() 
+0

其中代碼使用這個 – Ben

+0

對不起,剛添加它。 – user3754248

+0

調試提示。將update語句添加到update()並觀察maxypos的值如何更改。 –

回答

0

此行並沒有太大的意義:

self.maxypos = self.yvel - (9.8 * self.th) 

保持簡單;試着這麼做:

self.maxypos = max(self.maxypos, self.ypos) 

後更新self.ypos。您還需要在__init__中初始化self.maxypos = self.ypos

你不需要所有這些微不足道的getter;只需訪問屬性(Python is not Java)。