import time
def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = "{:02d}:{:02d}".format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("Time ended.")
您在上面看到的這個 Python 代碼作業順利,并且從 given 開始倒計時time_sec。此代碼還每秒清潔一次螢屏。我想撰寫在 Ruby 中作業完全相同的代碼。
#timer.rb(Ruby codes) here
def countdown time_sec
while time_sec
mins, secs = time_sec.divmod(60)[0], time_sec.divmod(60)[1]
timeformat = "d:d" % [mins, secs]
puts "#{timeformat}\r"
sleep(1)
time_sec -= 1
end
puts "Time is ended."
end
您在上面看到的這個 Ruby 代碼以錯誤的方式作業。首先,秒數一個接一個地列印。但我想像上面的 Python 代碼一樣更新單行代碼。其次,當這段 Ruby 代碼運行并達到倒計時時00:00,它會一直倒計時-01:59。如何更正此代碼?
uj5u.com熱心網友回復:
您正在使用puts,它添加了一個行尾并弄亂了\r. 此外,Python 代碼一直運行到 time_sec 為零,其評估結果為 false 并導致回圈停止。在 Ruby 中,零不會評估為假。
def countdown(time_sec)
time_sec.downto(0) do |t|
print "d:d\r" % t.divmod(60)
sleep 1
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489093.html
