簡體   English   中英

(Python)使用取模來獲取從更改秒到小時和分鍾的余數

[英](Python) Using modulo to get the remainder from changing secs, to hrs and minutes

我目前剛開始學習python,卻偶然發現了這個問題:

練習2-7獲取時間編寫一種算法,該算法讀取以秒為單位的時間量,然后顯示等效的小時,分​​鍾和剩余的秒數。 •一小時對應60分鍾。 •一分鍾對應60秒。

這是我的寫法:

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)

有人告訴我,有一種更簡單的方法可以使用模來編寫,以便在幾分鍾和幾秒鍾內得到剩余的數據,有人可以幫忙嗎? 謝謝!

這只是“煩惱”,因為我沒有現在可以使用的測試系統。

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”的作用是:

  1. 取t除以60
  2. 刪除點的所有剩余內容
  3. 乘以60

帶數字:

  1. 5000/60 = 83.33333
  2. => 0.33333
  3. 0.33333 * 60 = 20

您對分鍾數的計算無法正常工作,您需要在小時數中使用Modulo。 您可以用幾分鍾來做,就像用秒來代替一樣:

m =     (t - h * 3600) // 60
s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds

並建立結果字符串有更好的方法,例如

print '{}:{}:{}.{}'.format(h,m,s,ms)

如果您查看以下內容,則可以找到格式化的更多方法和選項:

用於字符串格式化的python dokumentation

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM