1 python
好吧,所以我在我的桌子上敲了几天这个,我仍然无法得到它我一直遇到这个问题:
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 44, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 35, in main
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in __init__
builtins.TypeError: can't multiply sequence by non-int of type 'float'
Run Code Online (Sandbox Code Playgroud)
一遍又一遍.我想我已经碰到了墙,我确实做了很多寻找和测试,但如果有人能指出我正确的方向,我将不胜感激.
from math import pi, sin, cos, radians
def getInputs():
a = input("Enter the launch angle (in degrees): ")
v = input("Enter the initial velocity (in meters/sec): ")
h = input("Enter the initial height (in meters): ")
t = input("Enter the time interval between position calculations: ")
return a,v,h,t
class Projectile:
def __init__(self, angle, velocity, height):
self.xpos = 0.0
self.ypos = height
theta = pi *(angle)/180
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):
"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 main():
a, v, h, t = getInputs()
cball = Projectile(a, v, h)
zenith = cball.getY()
while cball.getY() >= 0:
cball.update(t)
if cball.getY() > zenith:
zenith = cball.getY()
print ("/n Distance traveled: {%0.1f} meters." % (cball.getY()))
print ("The heighest the cannon ball reached was %0.1f meters." % (zenith))
if __name__ == "__main__": main()
Run Code Online (Sandbox Code Playgroud)
您的输入函数返回字符串,而不是数字类型.您需要首先将它们转换为整数或浮点数.
我认为你所看到的特殊错误是当你试图计算theta时.您将pi(浮点数)乘以角度(它包含一个字符串).该消息告诉您不能将字符串乘以浮点数,但可以将字符串乘以int.(例如,"spam" * 4给你"spamspamspamspam",但"spam" * 3.14没有任何意义.)不幸的是,这不是一个非常有用的信息,因为对你而言,它不是pi,它是错误的类型,而是角度,它应该是一个数字.
您应该可以通过更改getInputs来解决此问题:
def getInputs():
a = float(input("Enter the launch angle (in degrees): "))
v = float(input("Enter the initial velocity (in meters/sec): "))
h = float(input("Enter the initial height (in meters): "))
t = float(input("Enter the time interval between position calculations: "))
return a,v,h,t
Run Code Online (Sandbox Code Playgroud)
我还应该注意,这是Python 2.*和Python 3.*具有不同行为的区域.在Python 2.*中,input读取一行文本,然后将其作为Python表达式进行评估,同时raw_input读取一行文本并返回一个字符串.在Python 3.*中,input现在执行raw_input之前的操作 - 读取一行文本并返回一个字符串.虽然"将其评估为表达式"行为可能对简单示例有所帮助,但除了一个微不足道的例子之外,它对任何事情都是危险的.用户可以输入任何表达式并对其进行评估,这可能会对您的程序或计算机产生各种意外情况.
| 归档时间: |
|
| 查看次数: |
327 次 |
| 最近记录: |