In Python, what is a good way to round towards zero in integer division?
问题 1/2 gives 0 as it should. However, -1/2 gives -1 , but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that? 回答1: Do floating point division then convert to an int. No extra modules needed. >>> int(float(-1)/2) 0 >>> int(float(-3)/2) -1 >>> int(float(1)/2) 0 >>> int(float(3)/2) 1 回答2: Python's default division of integers is return the floor (towards negative infinity) with no ability to change that. You can