Integer Division in Python: Why Do Division Results Round Down?
When dividing two integers in Python, the resulting value is automatically rounded to an integer. This can be confusing, especially when you expect a floating-point value.
The Explanation
Python's integer division truncates the decimal portion of the result. Thus, in the expression (20-10) / (100-10), both operands are integers, and the result is truncated to 0, which is then cast back to an integer.
How to Fix It
To obtain a floating-point result, you can cast one of the operands to a float:
float((20 - 10) / (100 - 10))
Alternatively, you can use Python's division import from the future module:
from __future__ import division (20 - 10) / (100 - 10)
This import changes the division operator to perform floating-point division, even when the operands are integers.
The above is the detailed content of Why Does Python's Integer Division Round Down?. For more information, please follow other related articles on the PHP Chinese website!