需要将总分钟数转换为小时和分钟格式
我需要帮助,把这个转换成小时和分钟的格式,使用余数运算符。我对Python和编程还比较陌生,所以非常感谢你的帮助。
#Define the value of our variables
numberOfEpisodes = 13
minutesPerEpisode = 42
#Calculate the results
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//minutesPerHour
#Display the output
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.') print('This is equivalent to', equivalency)
这是我现在的代码,我能算出有多少小时,但我不知道怎么调整代码来包括剩下的分钟。
抱歉如果我说得不太清楚,但希望你能理解。
3 个回答
1
使用取模运算符 %
#Define the value of our variables
numberOfEpisodes = 13
minutesPerEpisode = 42
#Calculate the results
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//60
minutes= totalMinutes%60
#Display the output
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.')
print('This is equivalent to', equivalency,minutes)
3
你可以使用 //
来进行整数除法,使用 %
来得到余数。想了解更多关于Python中 int
和 float
除法的内容,可以点击这里。
>>> numberOfEpisodes = 13
>>> minutesPerEpisode = 42
>>> totalMinutes = numberOfEpisodes * minutesPerEpisode
>>> totalMinutes
546
>>> minutesPerHour = 60
>>> totalHours = totalMinutes // minutesPerHour
>>> totalHours
9
>>> remainingMinutes = totalMinutes % minutesPerHour
>>> remainingMinutes
6
结果
>>> print('{} episodes will take {}h {}m to watch.'.format(numberOfEpisodes,totalHours, remainingMinutes))
13 episodes will take 9h 6m to watch.