在Python中,取整可以通过以下几种方法实现:
1. 向下取整(Floor):
使用内置函数 `int()`。
a = 3.75
print(int(a)) 输出:3
2. 向上取整(Ceiling):
使用 `math` 模块中的 `ceil()` 函数。
import math
x = 3.75
print(math.ceil(x)) 输出:4
3. 四舍五入取整:
使用内置函数 `round()`。
x = 3.5
print(round(x)) 输出:4
4. 分别取整数部分和小数部分:
使用 `math` 模块中的 `modf()` 函数。
import math
x = 3.25
print(math.modf(x)) 输出:(0.25, 3.0)
5. 取整到指定位数:
使用 `round()` 函数,并传入 `ndigits` 参数。
x = 3.
print(round(x, 2)) 输出:3.14
需要注意的是,`math.ceil()` 和 `math.floor()` 函数返回的是浮点数,而 `int()` 和 `round()` 函数返回的是整数。