浏览 3874 次
锁定老帖子 主题:python中的函数round
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-04-10
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,我就想知道这个理由,大家有什么见解讨论下。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2012-04-11
“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 |
|
返回顶楼 | |
发表时间:2012-04-12
喜羊羊与灰太狼 写道 “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 谢谢,原来python3是这样设计的,但是为什么要这样设计呢?其中的原因和好处是我不明白。 还有java中的round(),为什么round(-0.5)=0 round(-1.5)=-1呢,感觉都有点奇怪的。 是不是我可以不用考虑这些,只要记住用就可以了呢?但是说真的我真的想知道的呢。 |
|
返回顶楼 | |
发表时间:2012-04-12
刚找了下java中的的
Math.round()方法是先将参数加上0.5然后去取它的Math.floor()值, 所以round(-0.5)=floor(0)=0,而round(-0.6)=floor(-0.1)=-1; |
|
返回顶楼 | |
发表时间:2012-04-20
取小于它的最接近的整数
|
|
返回顶楼 | |