为什么这个Java部门打印出零?

问题描述:

我有以下代码行:

System.out.println(5/9);

我希望结果看到0.555,但它打印出零。有人能帮我理解为什么会这样吗?我目前正在学习编程并感谢他们的帮助。

I expect to see 0.555 as a result, but instead it prints out zero. Can someone help me understand why this happens? I am currently learning programming and appreciate the help.

谢谢!

这是因为你在不知不觉中做了什么是整数部门。
为了快速进行计算,当没有涉及十进制数时,计算机使用整数除法,因此十进制值丢失。

This happens because what you are unknowingly doing is Integer Division. To make calculations fast, computer uses Integer division method when there's no decimal number involved, and hence decimal values are lost.

试试这个:

System.out.println(5.0 / 9.0);

System.out.println(5.0 / 9);

System.out.println(5 / 9.0);

System.out.println((float) 5 / 9);

System.out.println(5 / (float) 9);