Python round()函数避坑

研究主题: Python中的round()函数用法及结果

Python版本信息:

Python 3.10.2 (main, Feb 2 2022, 06:19:27) [Clang 13.0.0 (clang-1300.0.29.3)]

IPython 8.2.0 – An enhanced Interactive Python. Type ‘?’ for help.

输入 help(round)可以得到下列信息:

Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.
说明: 上文信息表示round()是python中的一个内置函数, 可以把指定数字进行十进制下的四舍五入. 且可以接受最多两个参数
第一个参数: number 该参数必选, 表示要操作的数字
第二个参数: ndigits 该参数可选, 表示要保留的位数, 为空或等于None, 则保留为整型.

发现的问题

如果我们要保留小数点后x位, 则当第x + 1位是5的时候, 会产生很神奇的结果:

Python round()函数避坑_第1张图片

有时候向上取, 有时候又是向下取.

得出结论

最后经过实验, 总结出如下规律:

如果此时要保留 n d i g i t s ndigits ndigits位, 而小数点后第 n d i g i t s + 1 ndigits + 1 ndigits+1位是 5 5 5, 则判断小数点后 n d i g i t s + 2 ndigits + 2 ndigits+2位是否存在(且不为 0 0 0). 若存在则进位, 反之则看解释器心情.

例如:
r o u n d ( 5.3351 , 2 ) → 5.34 round(5.3351, 2) \rightarrow 5.34 round(5.3351,2)5.34
r o u n d ( 5.325 , 2 ) → 5.33 , r o u n d ( 5.345 , 2 ) → 5.34 round(5.325, 2) \rightarrow 5.33, round(5.345, 2) \rightarrow 5.34 round(5.325,2)5.33,round(5.345,2)5.34


我也浏览了其他博客, 其他博主有两种错误的理解:

1.看 n d i g i t s ndigits ndigits位的奇偶, 若偶数进位, 反之舍位
2.单纯看是否存在 n d i g i t s ndigits ndigits, 若存在进位, 反之舍位

以上说法是不正确的, 均在上图中体现出反例

END

你可能感兴趣的:(Python,python,函数)