(Python) 使用模数从更改秒到小时和分钟中获取余数
(Python) Using modulo to get the remainder from changing secs, to hrs and minutes
我目前刚开始学习 python 并且偶然发现了这个问题:
Exercise 2-7 Get the Time
Write an algorithm that reads the amount of time in seconds and then displays the equivalent
hours, minutes and remaining seconds.
• One hour corresponds to 60 minutes.
• One minute corresponds to 60 seconds.
我是这样写的:
def amount_time(t):
h = t//3600
m = int((t/3600 - h)*60)
s = int(((t/3600 - h)*60 - m)*60)
print("Number of hours:",h)
print("Number of minutes:",m)
print("Number of Seconds:", s)
amount_time(5000)
有人告诉我有一种更简单的方法可以使用模数来编写它以获得分钟和秒的余数,有人可以帮忙吗?谢谢!
这只是 "out of my head",因为我现在没有可以使用的测试系统。
def amount_time(t):
print("Number of Seconds:", t % 60)
print("Number of Minutes:", (t // 60) % 60)
print("Number of Hours:", (t // 3600))
"t % 60" 的作用:
- 取t,除以60
- 删除点左边的所有内容
- 乘以 60
有数字:
- 5000 / 60 = 83.33333
- => 0.33333
- 0.33333 * 60 = 20
您对分钟的计算不正确,您对小时使用模数。
你可以用分钟做同样的事情,就像你用秒代替一样:
m = (t - h * 3600) // 60
s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds
要构建结果字符串,有更好的方法,f.e。
print '{}:{}:{}.{}'.format(h,m,s,ms)
如果您在此处查看,您会发现更多格式化方式和选项:
我目前刚开始学习 python 并且偶然发现了这个问题:
Exercise 2-7 Get the Time Write an algorithm that reads the amount of time in seconds and then displays the equivalent hours, minutes and remaining seconds. • One hour corresponds to 60 minutes. • One minute corresponds to 60 seconds.
我是这样写的:
def amount_time(t):
h = t//3600
m = int((t/3600 - h)*60)
s = int(((t/3600 - h)*60 - m)*60)
print("Number of hours:",h)
print("Number of minutes:",m)
print("Number of Seconds:", s)
amount_time(5000)
有人告诉我有一种更简单的方法可以使用模数来编写它以获得分钟和秒的余数,有人可以帮忙吗?谢谢!
这只是 "out of my head",因为我现在没有可以使用的测试系统。
def amount_time(t):
print("Number of Seconds:", t % 60)
print("Number of Minutes:", (t // 60) % 60)
print("Number of Hours:", (t // 3600))
"t % 60" 的作用:
- 取t,除以60
- 删除点左边的所有内容
- 乘以 60
有数字:
- 5000 / 60 = 83.33333
- => 0.33333
- 0.33333 * 60 = 20
您对分钟的计算不正确,您对小时使用模数。 你可以用分钟做同样的事情,就像你用秒代替一样:
m = (t - h * 3600) // 60
s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds
要构建结果字符串,有更好的方法,f.e。
print '{}:{}:{}.{}'.format(h,m,s,ms)
如果您在此处查看,您会发现更多格式化方式和选项: