【问题标题】:don't know what my Error is (python)不知道我的错误是什么(python)
【发布时间】:2017-11-22 10:35:48
【问题描述】:

实现一个具有以下属性的类 Car。一辆车有一个 一定的燃油效率(以英里/加仑衡量)和一定的 油箱中的燃油量。效率在 构造函数,初始燃料水平为0。提供方法驱动 模拟驾驶汽车一定距离,减少 油箱中的燃料油位,以及 getGasLevel 方法,以返回 当前的燃油油位和 addGas 油箱。示例用法:

myHybrid = Car(50)
myHybrid.addGas(20)
myHybrid.drive(100)
print(myHybrid.getGasLevel())

编写一个主程序来测试你的类。

我的代码:

class Car(object):
    def __init__(self, fuelEfficiency):
        super(Car, self).__init__()
        self.fuelEfficiency = fuelEfficiency
        self.fuelLevel = 0  #   In gallons


    #   Returns the amount of gas
    def getGasLevel(self):
        return self.fuelLevel

    #   Adds gas
    def addGas(self, gasToAdd):
        self.fuelLevel += gasToAdd

    #   Simulates driving car for a given distance
    #   and reduces the amount of gas based on the
    #   fuelEfficiency.
    def drive(self, distanceInMiles):
        gasToRemove = self.fuelEfficiency * distanceInMiles

        self.fuelLevel -= gasToRemove

        #   Ensure we don't go below zero gas
        self.fuelLevel = max(self.fuelLevel,0)


def main():

    myHybrid=Car(50)
    myHybrid.addGas(20)
    myHybrid.drive(100)
    print(myHybrid.getGasLevel())

【问题讨论】:

  • 为什么你认为有一个“错误”?发生了什么事出乎你的意料?
  • 你为什么把它标记为python-2.7python-3.x?不能两者兼有。
  • 对不起,我是一个完整的初学者,所以我只是尝试在两个版本上标记它
  • asongtoruin,我没有得到任何价值
  • 你确定是你写的代码吗?如果你这样做了,你会感到惊讶的是,你的间距和 cmets 与这些家伙完全相同...github.com/MosheBerman/oop-1/blob/master/1.3/Car.py

标签: python python-2.7


【解决方案1】:

您实际上需要致电main()

在底部添加以下行(无缩进):

if __name__ == '__main__': 
    main()

【讨论】:

  • 您的代码正在运行,它输出0。它完全按照它应该做的事情,但正如另一个答案中指出的那样,你在数学上犯了错误。
【解决方案2】:

几件事:

  1. 您没有调用您的main()。我怀疑这是复制和粘贴错误。

  2. 你在减少燃料方面搞砸了。而不是self.fuelEfficiency * distanceInMiles,它应该是distanceInMiles / self.fuelEfficiency。您当前的代码是减去 100*50 加仑而不是 12 加仑。因此,很明显,您的燃料将变为 0。

新代码

class Car(object):
    def __init__(self, fuelEfficiency):
        super(Car, self).__init__()
        self.fuelEfficiency = fuelEfficiency
        self.fuelLevel = 0  #   In gallons

    #   Returns the amount of gas
    def getGasLevel(self):
        return self.fuelLevel

    #   Adds gas
    def addGas(self, gasToAdd):
        self.fuelLevel += gasToAdd

    #   Simulates driving car for a given distance
    #   and reduces the amount of gas based on the
    #   fuelEfficiency.
    def drive(self, distanceInMiles):
        gasToRemove = distanceInMiles / self.fuelEfficiency
        self.fuelLevel -= gasToRemove
        #   Ensure we don't go below zero gas
        self.fuelLevel = max(self.fuelLevel,0)


def main():
    myHybrid=Car(50)
    myHybrid.addGas(20)
    myHybrid.drive(100)
    print(myHybrid.getGasLevel())

if __name__ == '__main__': 
    main()

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多