python取整

该代码展示了Python中对除法运算的各种取整方法,包括普通除法、地板除法、四舍五入、向上取整和向下取整。测试函数test_round用于比较不同取整操作的结果,例如`//`操作符与`math.floor`得到相同结果,而`round`执行四舍五入,不考虑符号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import math

def test_round(a, b):
    print('-------------------------------------')
    print(f'{a}/{b}=', a/b)
    print(f'{a}//{b}=', a//b)
    print(f'round({a}/{b})=', round(a/b))
    print(f'int({a}/{b})=', int(a/b))
    print(f'ceil({a}/{b})=', math.ceil(a/b))
    print(f'floor({a}/{b})=', math.floor(a/b))

test_round(3, 2)
test_round(-3, 2)

结果:

-------------------------------------
3/2= 1.5
3//2= 1
round(3/2)= 2
int(3/2)= 1
ceil(3/2)= 2
floor(3/2)= 1
-------------------------------------
-3/2= -1.5
-3//2= -2
round(-3/2)= -2
int(-3/2)= -1
ceil(-3/2)= -1
floor(-3/2)= -2

//操作结果和floor是一样的。

ceil:坐标轴上向上取整

floor:向下取整

int:向中(0)取整(直接去掉浮点位)

round则是四舍五入(不考虑符号)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值