In Python, what is a good way to round towards zero in integer division?

前端 未结 8 1698
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 09:45
1/2

gives

0

as it should. However,

-1/2

gives

-1
8条回答
  •  我在风中等你
    2020-12-09 10:05

    Do floating point division then convert to an int. No extra modules needed.

    Python 3:

    >>> int(-1 / 2)
    0
    >>> int(-3 / 2)
    -1
    >>> int(1 / 2)
    0
    >>> int(3 / 2)
    1
    

    Python 2:

    >>> int(float(-1) / 2)
    0
    >>> int(float(-3) / 2)
    -1
    >>> int(float(1) / 2)
    0
    >>> int(float(3) / 2)
    1
    

提交回复
热议问题