以下面的代码为例。
class Main {
public static void main(String[] args) {
int i = 41;
long l = i*9/5; //no explicit type casting required
float f = i*9/5; //no explicit type casting required
double d = i*9/5; //no explicit type casting required
double e = (double) i*9/5;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
System.out.println("Double value "+d);
System.out.println("Double value cast "+e);
}
}
目标类型大于源类型,因此不需要显式转换,但是为什么会损失精度?为什么不能将
d
和f
设置为73.8?
最佳答案
从技术上讲,这里发生的不是loss of precision,而是integer division的使用。
让我们以f
的情况为例:float f = i*9/5;
因为乘法和除法运算符具有相同的优先级并且是左关联的,所以该语句等效于:float f = (i*9)/5;
因为i=41
和9
都是int
类型的,所以结果值的类型也是int
(369
)。因此,评估的下一步是369/5
。因为两个操作数的类型均为int
,所以/
运算符的解释是使用整数除法,该运算将丢弃任何小数余数。由于369/5 = 73 + 4/5
,表达式的计算结果为73
,然后将其转换为float
值73.0
并分配给f
。d
的过程非常相似,除了73
的最终转换是double
值73.0
。
请注意,尽管我在评估中包括了中间步骤,但是左缔合性对整数除法的使用没有影响。 float f = i*(9/5);
生成f = 41.0
。
关于java - Java中的加宽或自动类型转换;为什么会有精度损失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53770357/