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.
Feed/

Why does integer division truncate fractional results in Java?

No cover

Channel

Computer science one

1 page

"Special care must be taken when dealing with int types. For all four operators, if both operands are integers, the result will be an integer. For addition, subtraction, and multiplication this isn’t an issue, but for division it means that when we divide, say (10 / 20), the result is not 0.5 as expected. The number 0.5 is a floating point number. As such, the fractional part gets truncated, or cut off and thrown out, leaving only zero. In the code above, d = a / b; the variable d ends up getting the value zero because of this.\n\nA solution to this problem is to use explicit type casting to force at least one of the operands in an integer division to become a double type. For example:\n\nint a = 10, b = 20;\n\ndouble x;\n\nx = (double) a / b;"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.