我在这个方法工作流程中缺少什么?

时间:2014-06-18 21:32:15

标签: python

我正在学习如何使用书中的方法,在本练习中我试图找到弹丸的最大高度。我很确定我把这个等式放到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()

1 个答案:

答案 0 :(得分:0)

这条线没有多大意义:

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

保持简单;尝试类似的事情:

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

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

你不需要所有那些微不足道的吸气剂;只需访问属性(Python is not Java)。