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

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

gives

0

as it should. However,

-1/2

gives

-1
8条回答
  •  感情败类
    2020-12-09 10:20

    Throwing my hat in with a few alternate ideas:

    Multiple the sign of the number [abs(x)/x] by the abs(x)/2

    (abs(x)/x)*(abs(x)/2)
    

    Perform the addition, but if the number is less than zero add one to shift it closer to 0.

    x/2 + int(x<0)
    

提交回复
热议问题