How can I divide without flooring in Java?

2019-07-19 16:58发布

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);

标签: java integer
4条回答
Summer. ? 凉城
2楼-- · 2019-07-19 17:13

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

System.out.println(5.0 / 18.0);
查看更多
Luminary・发光体
3楼-- · 2019-07-19 17:20

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);
查看更多
贪生不怕死
4楼-- · 2019-07-19 17:22

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

查看更多
该账号已被封号
5楼-- · 2019-07-19 17:27

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

查看更多
登录 后发表回答