如何将输出保持在小数点两位以下?
没有小数位:
import time
print ("60 SECOND TIMER")
run = input('click ENTER to run')
secs=0
while secs < 60:
print(60 - secs)
time.sleep(1)
secs = secs+1小数点两位:
import time
print ("60 SECOND TIMER")
run = input('click ENTER to run')
secs=0
while secs < 60:
print(60 - secs)
time.sleep(0.01)
secs = secs+0.01注意:小数点后两位开始疯狂(小数点的8或9位结束)。
发布于 2015-02-19 18:59:58
使用第()轮函数如下:
print(round(60 - secs, 2))将剩余时间输出到小数点后两位。
顺便说一句,每10毫秒打印一次可能有点乐观,因为你的显示器可能每秒钟更新60次,即每隔16.67毫秒更新一次。
发布于 2015-02-08 08:13:59
尝试time.sleep(.01 - timer() % .01),用timer()锁定睡眠。不过,如果time.sleep()或timer()都不支持10‘t的粒度,那就没有帮助了。它还可能取决于Python解释器如何在线程(GIL获取/发布)和OS调度器之间切换(系统有多忙,操作系统在进程/线程之间切换的速度有多快)。
要暂停很短的时间,可以尝试一个繁忙的循环:
from time import monotonic as timer
deadline = timer() + .01
while timer() < deadline:
pass例如,使用time.sleep()每10毫秒做一次事情可能会失败:
import time
from time import monotonic as timer
now = timer()
deadline = now + 60 # a minute
while now < deadline: # do something until the deadline
time.sleep(.01 - timer() % .01) # sleep until 10ms boundary
now = timer()
print("%.06f" % (deadline - now,))但是,基于繁忙循环的解决方案应该更精确:
import time
from time import monotonic as timer
dt = .01 # 10ms
time.sleep(dt - timer() % dt)
deadline = now = timer()
outer_deadline = now + 60 # a minute
while now < outer_deadline: # do something until the deadline
print("%.06f" % (outer_deadline - now,))
# pause until the next 10ms boundary
deadline += dt
while now < deadline:
now = timer()https://stackoverflow.com/questions/28386632
复制相似问题