温馨提示×

python round函数的用法有哪些

小亿
229
2023-08-22 21:14:31
栏目: 编程语言

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()函数时,需要注意浮点数的精度问题。

0