Python 中的round函数
2021/8/26 17:06:23
本文主要是介绍Python 中的round函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在python2.7的doc中,round()的最后写着,
"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0."
保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。
但是到了python3.5的doc中,文档变成了
"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice."
如果距离两边一样远,会保留到偶数的一边。比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。
Python 2.7 中的结果如下:
>>> round(-0.5)
-1.0
>>> round(0.5)
1.0
>>> round(1.5)
2.0
>>> round(2.5)
3.0
>>> round(3.5)
4.0
>>> round(4.5)
5.0
>>> round(6.5)
7.0
Python 3.8 中的结果如下:
round(-0.5)
0
round(0.5)
0
round(1.5)
2
round(2.5)
2
round(3.5)
4
round(4.5)
4
round(5.5)
6
round(6.5)
6
这篇关于Python 中的round函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python