python round函数的用法有哪些

寻技术 Python编程 2024年12月29日 49

Python的round()函数用于对浮点数进行四舍五入。

round()函数的常见用法有:

  1. round(x):对x进行四舍五入,返回一个整数。

  2. round(x, n):对x进行四舍五入,保留n位小数。当n为正数时,小数点后保留n位小数;当n为负数时,整数部分保留n位小数。

  3. round(x, None):对x进行四舍五入,返回最接近的整数值。

  4. round(x, -n):对x进行四舍五入,返回一个整数,保留到最近的10的n次方。

以下是一些示例:

x = 3.14159 print(round(x)) # 输出: 3 print(round(x, 2)) # 输出: 3.14 print(round(x, -1)) # 输出: 0 print(round(x, -2)) # 输出: 0 print(round(4.5)) # 输出: 4 print(round(4.5, 0)) # 输出: 4 print(round(4.51)) # 输出: 5 print(round(4.51, 1)) # 输出: 4.5

注意:在使用round()函数时,需要注意浮点数的精度问题。

关闭

用微信“扫一扫”