Python如何使用round()函数?代码示例

2021年3月28日13:46:44 发表评论 715 次浏览

本文概述

Python提供了一个内置函数:round()会四舍五入为给定的位数并返回浮点数, 如果没有提供四舍五入的位数, 则会将数字四舍五入为最接近的整数。

语法如下:

round(number, number of digits)

round()参数:

..1) number - number to be rounded
..2) number of digits (Optional) - number of digits 
     up to which the given number is to be rounded.

如果缺少第二个形参,则round()函数返回:

..a)如果仅给出一个整数, 即15, 那么它将四舍五入为15。

..b)如果给出了一个十进制数,那么如果十进制值>=5,它将四舍五入到整数,如果十进制值<5,它将四舍五入到整数下限。

如果缺少第二个参数, 则下面是round()函数的python实现。

Python3

# for integers
print ( round ( 15 ))
 
# for floating point
print ( round ( 51.6 ))
 
 
print ( round ( 51.5 )) 
 
print ( round ( 51.4 ))

输出如下:

15
52
52
51

当第二个形参出现时,它返回:

当第(ndigit + 1)位数字> = 5时, 四舍五入到的最后一个十进制数字将增加1, 否则保持不变。

如果存在第二个参数, 则下面是round()函数的python实现

Python3

# when the (ndigit+1)th digit is =5
print ( round ( 2.665 , 2 ))
 
# when the (ndigit+1)th digit is >=5
print ( round ( 2.676 , 2 )) 
 
# when the (ndigit+1)th digit is <5
print ( round ( 2.673 , 2 ))

输出如下:

2.67
2.68
2.67

错误与异常

TypeError:如果参数中除了数字以外的任何其他数字, 都会引发此错误。

Python3

print ( round ( "a" , 2 ))

输出如下:

Runtime Errors:
Traceback (most recent call last):
  File "/home/ccdcfc451ab046030492e0e758d42461.py", line 1, in 
    print(round("a", 2))  
TypeError: type str doesn't define __round__ method

实际应用:

函数舍入的常见用途之一是处理小数和小数之间的不匹配。

舍入数字的一种用法是将1/3转换为十进制时, 将所有三个都缩短到小数点右边。在大多数情况下, 当需要使用小数点1/3时, 将使用四舍五入的数字0.33或0.333。实际上, 当十进制小数点与小数点不完全相等时, 通常只使用小数点右边的两位或三位数。你如何以小数点显示1/6?记住要四舍五入!

Python3

# practical application
b = 1 / 3
print (b)
print ( round (b, 2 ))

输出如下:

0.3333333333333333
0.33

注意:在python中, 如果我们不给第二个参数就将数字四舍五入到floor或ceil, 它将例如返回15.0, 而在Python 3中则返回15, 因此为了避免这种情况, 我们可以在python中使用(int)类型转换。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: