好的,所以我认为我对这种方式的想法太多了。剩下的代码就是我想要的(它做了我想要的事情),但是我似乎无法弄清楚如何计算分钟数。 因此,基本上,我应该从用户那里获得“行驶里程”和“每小时英里”。然后,我的程序应该确定在两行中以小时+分钟为单位的距离要花费多长时间(例如,一行上的“小时:”,另一行上的“分钟:”。我有“小时”想通了,但我想不通几分钟,我觉得这真的很简单,我只是想念它。
print("\nTravel Time Calculator")
miles = float(input("Enter Miles: "))
milesPh = float(input("Enter Miles Per Hour: "))
print("\nEstimated Travel Time")
if miles <= 0:
print("Miles must be greater than zero. Please try again.")
elif milesPh <= 0:
print("Miles per hour must be greater than zero. Please try again.")
else:
# calculate and display travel time
hours = round(miles / milesPh)
print("Hours: " + str(hours))
minutes = round()
print("Minutes: " + str(minutes))
答案 0 :(得分:1)
尝试一下:
print("\nTravel Time Calculator")
miles = float(input("Enter Miles: "))
milesPh = float(input("Enter Miles Per Hour: "))
print("\nEstimated Travel Time")
if miles <= 0:
print("Miles must be greater than zero. Please try again.")
elif milesPh <= 0:
print("Miles per hour must be greater than zero. Please try again.")
else:
# calculate and display travel time
hours = int(miles / milesPh)
print("Hours: " + str(hours))
minutes = ((miles / milesPh)*60) % 60
print("Minutes: " + str(minutes))
输出
Travel Time Calculator
Enter Miles: 20
Enter Miles Per Hour: 12
Estimated Travel Time
Hours: 1
Minutes: 40.0
答案 1 :(得分:1)
您可以通过潜水miles / milesPh
来轻松获得总时间。您的问题是您将其四舍五入还为时过早。
假装miles / milesPh = 5.5
。那是五个半小时。如果立即将其四舍五入,则会损失最后一个半小时。
因此,基本上,您必须具有一些系统来获取分钟数,之前您要舍入小时数。有两种直观的方法可以解决此问题:
(1)计算其引用的分钟数,并基于该分钟数来计算小时数:
total_minutes = (miles / milesPh) * 60 # total time in minutes
hours = total_minutes // 60 # integer division by 60 (drop the remainder)
minutes = int(total_minutes) % 60 # remainder after integer division by 60
(2)分别计算小时数和分钟数:
total_time = miles / milesPh # total time in hours
hours = int(total_time) # the integer part of total time is hours
minutes = int((total_time - hours) * 60) # the decimal part of total time becomes minutes