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

【Python基础】1.3.1 面向过程编程与面向对象编程(类)实例

2017-11-19 21:34 781 查看
语言:Python

IDE:Python.IDE

问题描述

铅球飞行问题:给定不同投掷角度与初始速度下,求解计算铅球的飞行距离

IPO描述

I:输入:铅球发射角度、初始速度与高度

P:模拟飞行,时刻更新铅球飞行位置

O:铅球飞行距离

面向过程编程

from math import pi,sin,cos,radians

def main()
angle=eval(input("Enter the launch angle:"))
vel=eval(input("Enter the initial velocity:"))
h0=eval(input("Enter the initial height:"))
time=eval(input("Enter the time interval:"))
#计算初始速度
xpos=0
ypos=h0

theta=radians(angle)
xvel=vel*cos(theta)
yvel=vel*sin(theta)
# 程序主循环
while ypos>=0:
xpos=xpos+time*xvel
yvell=yvel-time*9.8
ypos=ypos+time*(yvel+yvell)/2.0
yvel=yvell
print("\nDistance".format(xpos))     //format格式化字符串


面向对象编程(类)

from math import pi,sin,cos,radians

class Projectile:
def _init_(self,angle,valocity,height):             #建立一个投射体对象
self.xpos=0
self.ypos=h0

theta=radians(angle)
self.xvel=vel*cos(theta)
self.yvel=vel*sin(theta)

def update(self,time):                                #更新投射体状态
xpos=xpos+time*xvel
yvell=yvel-time*9.8
ypos=ypos+time*(yvel+yvell)/2.0
yvel=yvell

def getY(self):                                        #返回投射体角度
return self.ypos

def getX(self):                                        #返回投射体距离
return self.xpos

from projectile import *

def getInputs():
a=eval(input("Enter the launch angle:"))
v=eval(input("Enter the initial velocity:"))
h=eval(input("Enter the initial height:"))
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".format(shot.getX()))

if _main_=="_main_":
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 编程
相关文章推荐