Floor division with negative number

后端 未结 4 2274
夕颜
夕颜 2020-11-27 22:14

The expression 6 // 4 yields 1, where floor division produces the whole number after dividing a number.

But with a negative number, why do

4条回答
  •  旧时难觅i
    2020-11-27 22:31

    A useful way to understand why floor division // yields the results it does for negative values is see this as complimenting the modulo, or remainder, % operator.

    5/3  is equivalent to 1 remainder 2 
    

    i.e.

    5//3 = 1
    5%3 = 2
    

    But

    -5/3 = -2
    -5%3 = 1
    

    Or

    -2 + 1/3rd which is -1.6667 (ish)
    

    It can seem strange, but it ensures results such as -2,-2,-2,-1,-1,-1,0,0,0,1,1,1,2,2,2,3,3,3 etc. when generating sequences.

提交回复
热议问题