0
import time
def timer():
    a = 300.0
    while a > 0: #stopes at 0
        print(a)
        time.sleep(0.11) #for roughly 100 millisecond
        a = a - 0.1
timer()

我编写了一段代码,每 0.100 秒倒计时 1/10(大约。它必须大于 0.100,否则脚本会忽略它)。但是,输出如下所示:

300.0
299.9
299.79999999999995
299.69999999999993
299.5999999999999
299.4999999999999
299.39999999999986
299.29999999999984
299.1999999999998
299.0999999999998
298.9999999999998
298.89999999999975
298.7999999999997
298.6999999999997
298.5999999999997
298.49999999999966
298.39999999999964
298.2999999999996
298.1999999999996
298.09999999999957
297.99999999999955
297.8999999999995
297.7999999999995
297.6999999999995
297.59999999999945
297.49999999999943
297.3999999999994
297.2999999999994
297.19999999999936
297.09999999999934
296.9999999999993
296.8999999999993
296.7999999999993
296.69999999999925
...

为什么?有解决办法吗?

4

1 回答 1

1

您实际上可以使用一个名为round. round 函数将有效地四舍五入 9999999... 并且只显示你想要的。

代码的修订版本将是:

import time
def timer():
    for a in range(3000,0,-1):
        print(round(a*.1, 1))
        time.sleep(0.101) #for roughly 1 millisecond


timer()

要使用该round功能,请执行以下操作:

round([variableornumber]*.[float], [numberofdecimals]) #in this example, its limited to 1

使用时的另一种print方法round

print(round([variableornumber]*.[float], [numberofdecimals]))

python 创建的原因999999999999...是因为 python 无法以 2 为底创建 1/10 的精确分数。

15.Floating Point Arithmetic:问题与局限--python 3.8.2

于 2020-03-06T00:00:08.597 回答