Java中的浮点数是什么?

2022-01-09 00:00:00 floating-point java

我写了这段代码:

float b = 3.6;

我明白了:

<上一页>错误:未解决的编译问题:类型不匹配:无法从 double 转换为 float

为什么?float的定义是什么?

解决方案

在 Java 中,当您键入一个十进制数为 3.6 时,它会被解释为一个 double.double 是 64 位精度的 IEEE 754 浮点,而 float 是 32 位精度的 IEEE 754 浮点.由于 float 不如 double 精确,因此无法隐式执行转换.

如果你想创建一个浮点数,你应该以 f 结束你的数字(即:3.6f).

更多解释请参见Java教程的原始数据类型定义.

I wrote this code:

float b = 3.6;

and I get this:

Error:Unresolved compilation problem: 
    Type mismatch: cannot convert from double to float

Why? Whats the definition of float?

解决方案

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

相关文章