1. 程式人生 > >python中的函式round

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