I understand that in Java, if i divide two integers together, if the result isn't an integer, the fractional part is truncated and I get an integer result from the division.
This never made sense to me! I'm wondering if i could get some insight into why Java is designed to do this?
One of the answers here:
Why is the division result between two integers truncated?
Said that you usually expect an integer if you do an operation on two integers, but this just isn't true.
When calculating percentages, for example:(num_answers_correct / num_questions)
is an example with two integers where I expect a fraction.
It seems dangerous to me to have to be so aware of what type the variable num_answers_correct is, etc, especially in a high-level language.
It's easy to accidentally perform an integer division when you wanted floating-point division, but never vice-verca. Wouldn't it be less error-prone to make the programmer indicate they intend to truncate the result, rather than make the programmer:
- Realize that they are dividing two integers
- Force floating point division using a float cast (or something like that)?
In the link mentioned above, someone said that visual basic 6 does exactly this -- / is an operator that returns a double, and \ is an operator that does integer division. this person said it was too confusing to have two operators; I don't see how it would be confusing, though.
So, my questions:
- Do I have a valid argument? or am I missing something?
- Why does Java use integer division?
Could someone help me see?