java - char c = 一些整数文字可能会编译,但 float f = 一些浮点文字永远不会编译。为什么?

标签 java floating-point type-conversion character literals

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 .

JLS 5.2

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/

相关文章:

java - 如何在非Spring的构造型类中使用@Autowired

c++ - 这种与浮点文字零的比较有效吗?

在指数和小数部分具有不同位数的格式之间转换

javascript - 将字符串转换为 boolean 值

c++ - Long Long 数据类型的 Cuda 算术除法错误

java - 如何通过对值施加任何条件将 2 个 HashMap 添加到 1 个 HashMap

java - 如何在 artifactory 中配置更长的版本号

java - 如果出现不同的字符,如何拆分字符串?

python - 从以两个十六进制字符串传输的 C double 转换

string - 在HashMap中将char用作&str