0
class car():
def __init__(self,make,model,year,fuel_capacity,perkilometer):
self.make = make
self.model = model
self.year = year
self.fuel_capacity = fuel_capacity
self.perkilometer = perkilometer
self.fuel_level = 0
def fill_tank(self):
"""fills the tank full capacity"""
self.fuel_level = self.fuel_capacity
print 'Tank is Full'
def drive(self):
"""drives untill out of gas"""
print 'car is moving'
i = 0
while 0 <= self.fuel_level:
self.fuel_level -= self.perkilometer
print '%s kilometres' % (self.fuel_level-(self.fuel_level-i))
i+=1
print 'out of gas'
def travel(self,kilometer):
"""travels for distance given"""
self.kilometer = kilometer
print 'Car is moving'
i=0
while 0!=kilometer:
kilometer-=1
i+=1
if self.fuel_level >= self.perkilometer:
self.fuel_level -= self.perkilometer
print '%s kilometres' % (kilometer - (kilometer - i))
elif self.fuel_level < self.perkilometer:
self.fuel_level=0
print 'Out of Gas'
return 0
elif self.fuel_level == 0:
print 'Out of Gas'
return 0
print 'Reached to destination'
def continue_driving(self):
distance_left = self.kilometer - self.fuel_level/self.perkilometer
leters_needed = distance_left * self.perkilometer
if distance_left<=self.fuel_level/self.perkilometer:
print 'Have enough gas to continue'
else:
print 'Need %s leter more'% leters_needed
def update_fuel_level(self,new_level):
if new_level <= self.fuel_capacity:
self.fuel_level = new_level
print 'Tank has %s leters' % self.fuel_level
else:
print "Tank can't hold that much"
def add_fuel(self,amount):
"""adds fuel to gas tank"""
if self.fuel_level+amount<=self.fuel_capacity:
self.fuel_level+=amount
print 'Added fuel %s leters '%amount
else:
print "Tank won't hold that much"
#somehow fuel level is not updating after or in add_fuel func.
my_car = car('hyundai','i20','2016','45',0.083)
my_car.fuel_level = 2
my_car.travel(50)
my_car.add_fuel(1)
my_car.continue_driving()
OUTPUT:Python變量在功能上沒有更新
Car is moving
1 kilometres
2 kilometres
3 kilometres
4 kilometres
5 kilometres
6 kilometres
7 kilometres
8 kilometres
9 kilometres
10 kilometres
11 kilometres
12 kilometres
13 kilometres
14 kilometres
15 kilometres
16 kilometres
17 kilometres
18 kilometres
19 kilometres
20 kilometres
21 kilometres
22 kilometres
23 kilometres
24 kilometres
Out of Gas
Added fuel 1 leters
Need 3.15 leter more
我在Python做這個車,但是當我用continue_driving
方法好像fuel_level
沒有更新找不到錯誤。
主要是我正在努力實現的是計算如果油箱中的氣體足夠或不用於乘坐如果不加油箱。
正如你可以看到,當我運行這段代碼,它說我們需要3.15升以上,但它應該是8.3/2 - (1 + 2)= 2.15
leters_needed沒有考慮目前的燃料量考慮在內。你總共需要3.15,這就是它打印的內容。您需要從中減去當前的燃油量,以獲得更多的燃油需求。 –
當您用完氣體時,您將self.fuel_level設置爲0.然後添加1升。然後,您計算出的距離爲50 - 1/0.083〜= 38。然後,您計算所需公升爲38 * 0.083 = 3.154。查看我的答案以獲取更多細節和解決方案。 – Joshua