python中的函数round

     今天在比较python3.2和Python2.7的区别的时候,发现了一个小插曲。代码如下。

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> round(1.0/2)
1.0
>>> round(3/2)
1.0
>>> round(3.0/2)
2.0
>>>


Python 3.2.2 (default, Sep  4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> round(1.0/2)
0
>>> round(3/2)
2
>>> round(3.0/2)
2
>>>

其中我就一点想不明白,为什么在python3.2中round(1.0/2)的值为0.我想python3这样写肯定有它的理由,不会是一个小bug,我就想知道这个理由。

论坛讨论的结果如下:
“For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as x. ”
所以两端差相等时,会round成偶数那端
>>> round(0.5)
0
>>> round(2.5)
2
>>> round(1.5)
2


你可能感兴趣的:(python)