Py学习  »  Python

为什么python中的round()函数会给出不同的结果?

rofelia09 • 5 年前 • 1714 次点击  

我尝试使用float数的循环,但是在python中,对于不同的float值,它会给出不同的结果。例子:

>>> round(4.5)
4

>>> round(3.5)
4

如你所见 round(4.5) 返回 4 虽然 rount(3.5) 返回 . 如何解决这个问题。我想要 回合(4.5) 归来 5 . 请帮帮我。谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46114
 
1714 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Amadan
Reply   •   1 楼
Amadan    6 年前

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)
Sraw
Reply   •   2 楼
Sraw    6 年前

official doc .

基本上它叫偶数圆。它会变圆的 x.5 价值转化为公平选择。

这里是 why .