Java打破了强类型化!谁能解释呢?
2022-09-03 04:23:47
可能的重复:
改变行为以可能损失精度
我在编译时发现了Java强类型检查的不一致。请看下面的代码:
int sum = 0;
sum = 1; //is is OK
sum = 0.56786; //compile error because of precision loss, and strong typing
sum = sum + 2; //it is OK
sum += 2; //it is OK
sum = sum + 0.56787; //compile error again because of automatic conversion into double, and possible precision loss
sum += 0.56787; //this line is does the same thing as the previous line, but it does not give us a compile error, and javac does not complain about precision loss etc.
任何人都可以向我解释一下吗?它是已知的错误,还是所需的行为?C++发出警告,C# 发出编译错误。
Java会破坏强类型吗?您可以将 += 替换为 -= 或 *= - 编译器可以接受所有内容。