为什么用小数倒数会得到 xxx.999999999999999999x?

Why does counting down in decimals result in a xxx.9999999999999999999x?

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
...

为什么?有修复吗?

您实际上可以使用名为 round 的 python 函数。 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

使用 roundprint 的另一种方法:

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

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

15.Floating Point Arithmetic: issues and limitations--python 3.8.2