why integer division java? [closed]

扶醉桌前 提交于 2019-12-10 17:32:50

问题


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:

  1. Do I have a valid argument? or am I missing something?
  2. Why does Java use integer division?

Could someone help me see?

来源:https://stackoverflow.com/questions/22341128/why-integer-division-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!