如何无限循环这个Python程序,并将浮点时间转换为小时和分钟?

时间:2017-03-15 22:44:53

标签: python loops time calculator

所以我需要制作一个燃油消耗计算器,它也会计算在特定行程上花费的时间。

我无法弄清楚如何让程序告诉我在"小时:分钟"格式而不仅仅是几个小时的浮点变量。

Time traveled: 1.6666666666666667 hours 应该 Time traveled: 1h:45min

此外,我不确定如何让程序重复问题并无限制地给出结果直到关闭。

这是我的代码:

# Get L/100km used from the user
fuel = input("Enter car's L/100kmh:")
fuel = float(fuel)

# Get distance driven from the user
distance = input("Enter kilometers driven:")
distance = float(distance)

# Get speed used from the user
speed = input("Enter driving speed:")
speed = float(speed)

# Calculate and print the answer
time = distance / speed
fuel_burned = distance / 100 * fuel
print("Time traveled:", time,"hours")
print("Fuel burned:", fuel_burned,"liters")

2 个答案:

答案 0 :(得分:1)

你可以将它包裹在while循环中。你的标题没有意义,因为这与GUI(图形用户界面)

无关

实施例

while True: 

    # Get L/100km used from the user
    fuel = input("Enter car's L/100kmh:")
    fuel = float(fuel)

    # Get distance driven from the user
    distance = input("Enter kilometers driven:")
    distance = float(distance)

    # Get speed used from the user
    speed = input("Enter driving speed:")
    speed = float(speed)

    # Calculate and print the answer
    time = distance / speed
    fuel_burned = distance / 100 * fuel
    print("Time traveled:", time,"hours")
    print("Fuel burned:", fuel_burned,"liters")

答案 1 :(得分:-3)

此代码已经过大量编辑,以尽可能准确。我的解决方案假设您希望能够正常退出程序,而不是让它在系统关闭时终止,但如果不是这样,只需从again = ...开始删除循环的最后部分。 / p>

while True:
    # Get L/100km used from the user
    fuel = input("Enter car's L/100kmh:")
    fuel = float(fuel)

    # Get distance driven from the user
    distance = input("Enter kilometers driven:")
    distance = float(distance)

    # Get speed used from the user
    speed = input("Enter driving speed:")
    speed = float(speed)

    # Calculate and print the answer
    time = distance / speed
    fuel_burned = distance / 100 * fuel
    hours = int(time)
    minutes_remainder = (time - hours) * 60
    minutes = int(minutes_remainder) 
    print("Time traveled: ", hours,":",minutes)
    print("Fuel burned: ", fuel_burned," liters")

     again = input("Go again? (y/n)")
     if again == "n":
        break

Here是一个将十进制小时转换为小时的示例:mins:C ++中的秒数,我用它来得到我给出的解决方案。