Java 规范示例中的错误?
The error in example of Java Specification?
原始类型转换主要有两种:
- 扩大转化;
- 缩小转换范围。
我在 Java SE Specification 中阅读有关扩大转换的内容,在这里我看到了以下图片:
int big = 1234567890;
float approx = big; // good, it's widening conversion (int -> float)
System.out.println(big - (int)approx); // what? (float -> int)
在最后一行代码中,我认为它是 narrowing 转换,对吗?如果我错了,请解释我!提前致谢。
是的,last 行使用了缩小转换,这就是为什么需要强制转换的原因。例子用来演示中间线上的拉宽转换丢失信息,仅此而已:
This program prints -46
thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.
原始类型转换主要有两种:
- 扩大转化;
- 缩小转换范围。
我在 Java SE Specification 中阅读有关扩大转换的内容,在这里我看到了以下图片:
int big = 1234567890;
float approx = big; // good, it's widening conversion (int -> float)
System.out.println(big - (int)approx); // what? (float -> int)
在最后一行代码中,我认为它是 narrowing 转换,对吗?如果我错了,请解释我!提前致谢。
是的,last 行使用了缩小转换,这就是为什么需要强制转换的原因。例子用来演示中间线上的拉宽转换丢失信息,仅此而已:
This program prints
-46
thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.