您的位置:首页 > 编程语言 > Python开发

python通过面向对象程序设计方法 实现铅球运行轨迹的计算

2016-04-29 10:53 846 查看
本文我们通过面向对象程序设计的方法,实现铅球运行轨迹计算的程序。

这个问题中有一个铅球对象,它有4个属性:xpos,ypos,xvel,yvel

构建投射体的类Projectile用来生成铅球对象,不断的更新对象变量,以此来描述这个问题。

用python3编写Projectile.py文件和main_qianqiu.py文件。

Projectile.py文件如下:

from math import sin,cos,radians

class Projectile:

def __init__(self,angle,velocity,height):

#根据给定的发射角度,初始速度和位置创建一个投射体对象

self.xpos=0.0

self.ypos=height

theta=radians(angle)

self.xvel=velocity*cos(theta)

self.yvel=velocity*sin(theta)

def update(self,time):

#更新投射体的状态

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

#返回投射体的y轴坐标

return self.ypos

def getX(self):

#返回投射体的x轴坐标(即水平距离)

return self.xpos

找到python的安装目录,将Projectile.py文件放到文件夹python35/Lib中,如下图:



main_qianqiu.py文件内容如下:

from Projectile import *

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

return a,v,h,t

def main():

angle,vel,h0,time=getInputs()

shot=Projectile(angle,vel,h0)

while shot.getY()>=0:

shot.update(time)

print('\nDistance traveled:{0:0.1f} meters.'.format(shot.getX()))

if __name__=='__main__':

main()

运行main_qianqiu.py文件,输入输出如下:



(完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: