问题
I'm currently new to learning python and stumbled upon this problem:
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.
Here's how I wrote it:
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)
I was told there was an easier way to write it using modulo to get the remainder for the minutes and seconds, could someone help? Thanks!
回答1:
This is just "out of my head", because I got no testing system I could use right now.
def amount_time(t):
print("Number of Seconds:", t % 60)
print("Number of Minutes:", (t // 60) % 60)
print("Number of Hours:", (t // 3600))
What "t % 60" does:
- take t, divide it by 60
- remove everthing left of the dot
- multiply with 60
With numbers:
- 5000 / 60 = 83.33333
- => 0.33333
- 0.33333 * 60 = 20
回答2:
Your calculation of minuts doesnt work correct, you use Modulo with the hours. You could do the same with minutes as you did wirh seconds instead:
m = (t - h * 3600) // 60
s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds
and to build the result string there are better ways, f.e.
print '{}:{}:{}.{}'.format(h,m,s,ms)
You find more ways and options to Format, if you look here:
python dokumentation for string formatting
来源:https://stackoverflow.com/questions/40084887/python-using-modulo-to-get-the-remainder-from-changing-secs-to-hrs-and-minute