Bifalgorithm post · Computer science one · Operators
Why does integer division truncate fractional results in Java?
Why does integer division truncate fractional results in Java? (Computer science one · Operators) — "Special care must be taken when dealing with int types. Fo…
Ideas in this flowchart
- Special care is required when working with integer types.
- When both operands are integers, all four operators produce an integer result.
- For addition, subtraction, and multiplication, an integer result is not generally a problem.
- Integer division cannot directly produce a fractional result.
- The fractional part is truncated, leaving only the integer portion.
- For example, 10 / 20 does not produce the expected value 0.5.
- Because 0.5 is a floating-point number, the expression d = a / b gives d the value zero.
- Explicit type casting provides a solution to the integer-division problem.
- At least one operand must be converted to the double type.
- With int a = 10, b = 20 and x = (double) a / b, the division uses a double operand.