char c1 = 123; //Compiles fine
char c2 = 123456; //Error: cannot convert from int to char
Java 足够聪明,可以判断一个整数是否小到可以转换为字符。为什么它不能将非常小的浮点文字转换为 float ?。例如:
float f1 = 0.3; //Error: cannot convert from double to float
float f2 = 0.3f; //Compiles fine
char c = 一些整数文字可能会编译,但 float f = 一些浮点文字永远不会编译。为什么?
PS:我知道默认情况下浮点字面量被视为 double
最佳答案
0.3
被视为 double,所以它的二进制表示需要 64 位,并且它不能在不损失精度的情况下放入 float,所以你不能将它分配给 float 变量没有明确的强制转换。
另一方面,如果您将 char 类型范围内的 int 文字(例如 123)分配给 char 变量,则不会丢失数据。
两个赋值(int 到 char 变量和 double 到 float 变量)都需要 narrowing primitive conversion .
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
关于java - char c = 一些整数文字可能会编译,但 float f = 一些浮点文字永远不会编译。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092559/