首页 > 解决方案 > python for循环增量值不是同一个输入

问题描述

start = 0.65

end = 0.75

step = 0.01

while start <= end:

    print (start)

    start += step

但是为什么我会低于?真的

0.65

0.66

0.67

0.68

0.6900000000000001

0.7000000000000001

0.7100000000000001

0.7200000000000001

0.7300000000000001

0.7400000000000001

0.0000000000000001 是从哪里来的?

多谢!

标签: pythonwhile-loop

解决方案


这个问题在此之前已经得到解答。总之,它与值的存储方式有关,因此 0.1 实际上存储为 0.1000000000000000055511151231257827021181583404541015625 因此为什么最后会得到额外的 1。您可以点击链接查看更多内容。要解决这个问题,可以使用内置的round函数。像这样:

start = 0.65

end = 0.75

step = 0.01

while start <= end:

    print (start)

    start = round(start + step, 2) # this rounds the answer to the nearest hundredth

希望这有帮助!


推荐阅读