问题描述
我了解如何在IDLE中键入此内容,但我并不真正理解其背后的数学原理。具体来说是第8行和第11行...有人可以指导我完成此操作,以便我了解此处正在进行的基本数学运算吗?
# Get a number of seconds from the user.
total_seconds = float(input('Enter a number of seconds: '))
# Get the number of hours.
hours = total_seconds // 3600
# Get the number of remaining minutes.
minutes = (total_seconds // 60) % 60
# Get the number of remaining seconds.
seconds = total_seconds % 60
# display the results.
print('Here is the time in hours,minutes,and seconds:')
print('Hours:',hours)
print('Minutes:',minutes)
print('Seconds:',seconds)
解决方法
您似乎对模运算符感到困惑。另请参阅the docs和/或this question / post。
简而言之,模运算符将除法并返回除法的余数;如果没有余数,则返回0。
让我们逐步查看您的示例:
>>> total_seconds = 11730
>>> total_seconds / 3600
3.2583333333333333
因此,您有3个小时,小数部分指定了分钟和秒。
>>> total_seconds / 60
195.5
您已经知道您有3个小时的工作时间,可以将其删除
>>> (total_seconds / 60) - 3 * 60
15.5
与
相同>>> (total_seconds / 60) % 60
15.5
因此您得到了3小时15分钟半分钟,实际上是30秒。这正是
返回的内容>>> total_seconds % 60
30
请注意,//
是下限分割(返回标准分割/
的整数部分的斩波)。