- 为什么 c 的值是 2.0 和 2.5,尽管它们具有相同的数据类型
a/b 中的转换是如何发生的
public static void main(String[] args) { int a = 5,b=2; float c; c=a/b; System.out.println(c); c=(float)a/b; System.out.println(c); }
3 回答
The answer lies in understanding that despite declaring c as float, integer division still takes place with a/b. Integer division in Java truncates any fractional part (so it can remain an int). Only then is it implicitly converted to a float upon assignment to c, and 2.0 is printed.
The cast to a float in (float)a/b changes a to 5.0f and forces floating point division before the result is assigned to c, so the correct result 2.5 is printed.
在第一个语句中,a/b是计算的。由于两个变量都是整数,因此结果也是整数:2. 在您的第二条语句中,a首先转换为 afloat然后除以b. 由于其中一个值是 a float,因此结果也是 a float: 2.5。
第一个划分是 int / int --> int 结果。第二个是Float/int,--> Float 结果。