How can I divide without flooring in Java?

你说的曾经没有我的故事 提交于 2019-12-24 03:03:22

问题


I'm trying to divide an integer by an integer in Java and return a long result. I tried the following, but I keep getting "0".

System.out.println(Long.valueOf(5) / Long.valueOf(18));
System.out.println((long)5 / (long)18);

回答1:


It seems everyone has given the right answer, but you should note you can also do

System.out.println(5 / 18f)

Where f makes it a float

System.out.println(5 / 18d)

where d makes it a double




回答2:


You don't need a long, you need a double.

System.out.println(5 / 18.0);

or

System.out.println(5.0 / 18);

Of course this will work too:

System.out.println(5.0 / 18.0);



回答3:


Long is for "long" integer numbers. You should use float or double instead.




回答4:


Longs are still integral, you need a type that can handle decimals, use either float or double.

System.out.println(5.0 / 18.0);


来源:https://stackoverflow.com/questions/8706727/how-can-i-divide-without-flooring-in-java

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