Python3 math.ceil()、math.floor()、//、int()、round()取整问题

Python3 math.ceil()、math.floor()、//、int()、round()取整问题

1. 向上取整:math.ceil(),往较大的方向取
import math

math.ceil(2.1)
3
math.ceil(2.8)
3
math.ceil(-2.1)
-2
math.ceil(-2.9)
-2
2. 向下取整:math.floor(),往较小方向取
math.floor(2.1)
2
math.floor(2.9)
2
math.floor(-2.1)
-3
math.floor(-2.9)
-3
3. // 取整:往小的方向取
3//2
1
-3//2
-2

注意:若被除数为小数(float型),则结果也为小数(float型)

3.0//2
1.0
4.2//2
2.0
4. int() 取整:往 0 的方向取
int(2.1)
2
int(2.9)
2
int(-2.1)
-2
int(-2.9)
-2
5. round() 取整:四舍五入
round(2.1)
2
round(2.5)
2
round(2.6)
3

分析:发现 round() 的四舍五入对边界 .5 的处理与预判不一致,原因为 2.52.50 存储时为 2.449round() 四舍五入看小数点后第一位,因此结果为 2。

round(2.51)     # 2.51 进位
3

负数情况同上

round(-2.1)
-2
round(-2.5)
-2
round(-2.51)
-3
round(-2.6)
-3

指定小数点位数

round(2.6666)
3
round(2.6666, 0)    # 默认为 0 的整数,设置为 0 得到值相同浮点数
3.0
round(2.6666, 1)
2.7
round(2.6666, 2)
2.67
round(2.6666, 3)
2.667

注意:上示例 2.52.50 存储为 2.449 并不是所有 .5 情况都为 .449,需要进一步查阅相关资料(望大佬赐教,非常感谢)。

print(round(0.5), round(1.5), round(2.5))
0 2 2
print(round(0.675,2), round(1.675,2), round(2.675,2))
0.68 1.68 2.67

参考

CSDN 博客1

CSDN 博客2

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值