前言
Python做力扣的过程中经常用到浮点数转整数的操作,今天就来整理一下🚗
几种浮点数转整数的方法
- 使用
int()函数:int()函数将浮点数转换为整数,但会丢弃小数部分。例如:
float_num = 3.9
int_num = int(float_num)
print(int_num) # 输出: 3
- 使用
math.floor()函数:math.floor()函数返回不大于输入浮点数的最大整数。这实际上是对浮点数向下取整。 P.S. floor的意思是地板
import math
float_num = 3.9
int_num = math.floor(float_num)
print(int_num) # 输出: 3
- 使用
math.ceil()函数:math.ceil()函数返回不小于输入浮点数的最小整数。这实际上是对浮点数向上取整。
import math
float_num = 3.1
int_num = math.ceil(float_num)
print(int_num) # 输出: 4
- 使用
round()函数:round()函数返回最接近输入浮点数的整数。如果有两个整数与浮点数同样接近,则结果会向偶数方向取整(也称为银行家舍入法)。
float_num = 3.5
int_num = round(float_num)
print(int_num) # 输出: 4(而不是3!!)
最后
一般情况下,int()最经常使用了。
下次见咯。🍉