可能有损转换从double到float错误

时间:2017-06-09 02:56:19

标签: java

我在浮点数据类型中采用r = 7.5。它显示以下错误 enter image description here

任何人都可以帮助我显示错误的原因吗?

3 个答案:

答案 0 :(得分:1)

JLS 3.10.2中,定义浮点文字形式:

A floating-point literal is of type float if it is suffixed with an ASCII
letter F or f;otherwise its type is double and it can optionally be suffixed
with an ASCII letter D or d (§4.2.3).

所以float r=7.5不正确,因为7.5是双精度型,因此不会将其分配给浮动类型r。您可以将其更改为float r=7.5f' or 'double r=7.5 < / p>

答案 1 :(得分:0)

改为写float r = 7.5F;7.5F是一个float常量,可以在不损失精度的情况下分配给float变量。

答案 2 :(得分:0)

7.5是双字面值,因此r值在乘以时会提升为double。将double存储到变量SI将是一个将丢失数据的转换,即double to float

要将数据保持为float,请使用float literal,最后使用f,并在程序中包含所有float变量。

相关问题