我该如何编写保留人工时间的代码?

时间:2019-11-29 12:59:07

标签: python

我正在用python编写代码来测量D&D中的时间,但是它不能准确地保存时间,有时会在秒后给出一堆零,也无法使am pm功能正常工作

import time

hour=int(input("how many seonds is one hour in your D&D?"))
minutes = hour/60
hour_time=10
day_time="Am"
minutes_time=0.00
true = 1
while true == 1:
    time.sleep (minutes)
    if hour_time==12 and minutes_time==0:
        if day_time=="Am":
            day_time="Pm"
        else:
            day_time="Am"
    if minutes_time>0.59:
        minutes_time = 0
        if hour_time==12: 
            hour_time = 1
        else:
            hour_time = hour_time + 1
    else:
        minutes_time = minutes_time + 0.01
    print(minutes_time+hour_time,"",day_time)

1 个答案:

答案 0 :(得分:1)

您有时会得到很多零的原因是格式问题。您可以在Python中为数字指定格式,如下所示:

print("{:.2f}".format(minutes_time+hour_time),"",day_time)

之前:

10.33  Am
10.34  Am
10.35  Am
10.36  Am
10.370000000000001  Am
10.38  Am
10.39  Am
10.4  Am

之后:

10.16  Am
10.17  Am
10.18  Am
10.19  Am
10.20  Am
10.21  Am
10.22  Am
10.23  Am
10.24  Am
10.25  Am
10.26  Am

请注意,在程序运行期间,在minutes_time = minutes_time + 0.01中累积时会传播一个精度错误。 浮点数具有计算精度限制,例如,您可以摆脱使用Python的fractions.Fraction

以下是使用Fraction的代码的有效示例:

import time
from fractions import Fraction

hour=int(input("how many seonds is one hour in your D&D?"))
minutes = hour/60
hour_time=10
day_time="Am"
minutes_time=Fraction(0, 1)
true = 1
while true == 1:
    time.sleep (minutes)
    if hour_time==12 and minutes_time==0:
        if day_time=="Am":
            day_time="Pm"
        else:
            day_time="Am"
    if minutes_time>=Fraction(59, 100):
        minutes_time = 0
        if hour_time==12: 
            hour_time = 1
        else:
            hour_time = hour_time + 1
    else:
        minutes_time = minutes_time + Fraction(1, 100)
    print("{:.2f}".format(float(minutes_time)+hour_time),"",day_time)