2025年Python:类的定义与使用

Python:类的定义与使用类的定义与使用 cball Projectile angle vel h0 中 cball 传入给 self 一个炮弹从某个倾角射出计算水平位移和大致飞行时间的程序 projectile py from math import radians sin cos 类的定义 class Projectile def

类的定义与使用

cball = Projectile(angle, vel, h0)中, cball传入给self

一个炮弹从某个倾角射出计算水平位移和大致飞行时间的程序

# projectile.py
from math import radians, sin , cos

##############类的定义#######
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)
self.totaltime = 0.0

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
self.totaltime = self.totaltime + time

def getX(self):
return self.xpos

def getY(self):
return self.ypos
#############################

###############函数定义########
def getIputs():
a = float(input("Enter the lanuch angle (in degrees):"))
v = float(input("Enter the lanuch velocity (in meters/sec):"))
h = float(input("Enter the lanuch height (in meters):"))
t = float(input("Enter the internal between position calculations:"))
return a, v, h, t

def main():
angle, vel, h0, time = getIputs()
cball = Projectile(angle, vel, h0)
while cball.getY() >= 0:
cball.update(time)
print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))
print("\nTotal time spent is roughly: {0:0.1f} sceonds.".format(cball.totaltime))
#############################

###########函数调用###########
if __name__ == '__main__':
main()

运行示例:

'''
Enter the lanuch angle (in degrees):50
Enter the lanuch velocity (in meters/sec):1
Enter the lanuch height (in meters):50
Enter the internal between position calculations:1

Distance traveled: 2.6 meters.

Total time spent is roughly: 4.0 sceonds.

'''
编程小号
上一篇 2025-03-12 20:21
下一篇 2025-09-18 07:57

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/133069.html