1

好吧,所以我已经为这个问题在我的办公桌上敲了几天,但我仍然无法得到它我一直遇到这个问题:

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'

一遍又一遍。我想我已经碰壁了,实际上我已经做了很多查看和测试,但如果有人能指出我正确的方向,我将不胜感激。

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()
4

1 回答 1

8

您的输入函数返回字符串,而不是数字类型。您需要先酌情将它们转换为整数或浮点数。

我认为您看到的特定错误是您尝试计算 theta 时。您将 pi(浮点数)乘以角度(包含字符串)。该消息告诉您不能将字符串乘以浮点数,但可以将字符串乘以整数。(例如"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

我还应该注意,这是 Python 2.* 和 Python 3.* 具有不同行为的区域。在 Python 2.* 中,input读取一行文本,然后将其评估为 Python 表达式,同时raw_input读取一行文本并返回一个字符串。在 Python 3.* 中,input现在执行raw_input之前所做的 - 读取一行文本并返回一个字符串。虽然“将其评估为表达式”行为对于简单的示例可能会有所帮助,但对于除了微不足道的示例之外的任何事情都是危险的。用户可以输入任何表达式并对其进行评估,这可能会对您的程序或计算机做各种意想不到的事情。

于 2013-04-28T18:43:50.920 回答