我尝试使用float数的循环,但是在python中,对于不同的float值,它会给出不同的结果。例子:
>>> round(4.5) 4
和
>>> round(3.5) 4
如你所见 round(4.5) 返回 4 虽然 rount(3.5) 返回 四 . 如何解决这个问题。我想要 回合(4.5) 归来 5 . 请帮帮我。谢谢
round(4.5)
4
rount(3.5)
四
回合(4.5)
5
从 docs :
如果两个倍数相等,则向偶数选择进行舍入(例如,round(0.5)和round(-0.5)均为0,round(1.5)均为2)。
也就是说,python 3可以 "rounding half to even" .
你可以这样做“围捕”:
import math def round_up(x): return math.floor(x + 0.5)
见 official doc .
基本上它叫偶数圆。它会变圆的 x.5 价值转化为公平选择。
x.5
这里是 why .