前言

round()是python自带的一个函数,用于数字的四舍五入。

但是round()的输出结果与Python的版本有关:

在python3中,round(1.0/2.0)=0;在python2中,round(1.0/2.0)=1

$ python
Python 2.7.8 (default, Jun 18 2015, 18:54:19) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
1.0
$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
0

使用方法:round(number,digits)

  • digits>0,四舍五入到指定的小数位
  • digits=0, 四舍五入到最接近的整数
  • digits<0 ,在小数点左侧进行四舍五入
  • 如果round()函数只有number这个参数,等同于digits=0

四舍五入规则:

  • 要求保留位数的后一位<=4,则舍去3,如5.214保留小数点后两位,结果是5.21
  • 要求保留位数的后一位“=5”,且该位数后面没有数字,则不进位,如5.215,结果为5.21
  • 要求保留位数的最后一位“=5”,且该位数后面有数字,则进位,如5.2151,结果为5.22
  • 要求保留位数的最后一位“>=6”,则进位。如5.216,结果为5.22

例子:

需要注意的

round()函数对于5的处理方式有所不同,具体取决于其前一位数字的奇偶性。如果前一位数字为偶数,则直接舍去;如果前一位数字为奇数,则进位。例如:

round(2.5) # 输出2
round(3.5) # 输出4

因此,在使用round()函数时需要注意这一点。

x = eval(input())
n = eval(input())
print(round(x,n))

总结

到此这篇关于python中的round()函数用法详解的文章就介绍到这了,更多相关python round()函数用法内容请搜索本网站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本网站!

您可能感兴趣的文章:

  • 简单介绍Python中的round()方法
  • python中round函数保留两位小数的方法
  • python中round函数如何使用
  • Python中round()函数实现数值的四舍五入