2022年 11月 3日

python中的取整

虽然取整是各种语言中最基础的操作, 可是往往多了一个1或者少了一个1会导致巨大的灾难,所以我觉得还是很有必要写一下的。
python中的取整操作有://, round, int, ceil, floor, 其他语言也有类似的函数来进行取整。先看一段代码:

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

打印结果:

-------------------------------------
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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

可以看出, //操作结果和floor是一样的。
总的来说, ceil:坐标轴上向上取整, floor:向下取整, int:向中(0)取整(直接去掉浮点位)。
而round则是四舍五入(不考虑符号)