请看下面的三行代码。
float f = 1;
float g = 1.1;
float h = 1.1f;
第二行有编译错误,其他行没有编译错误。第一行在没有后缀 f 的情况下工作正常,第三行在使用后缀 f 的情况下工作。这是为什么?
最佳答案
默认情况下,Java 中的浮点文字是一个 double
值。
JLS 3.10.2 Floating-Point Literals
A floating-point literal is of type
float
if it is suffixed with an ASCII letterF
orf
; otherwise its type isdouble
and it can optionally be suffixed with an ASCII letterD
ord
.
如果没有显式收缩转换,您不能将 double
值分配给 float
。因此,您有两个选择:
- 对于文字,使用后缀
f
或F
来表示float
值 - 对于非文字,使用显式转换
(float)
后者的一个例子是:
double d = 1.1;
float f = (float) d; // compiles fine!
关于扩大转化
编译的原因:
float f = 1;
是因为从 int
到 float
的扩展转换可以在赋值上下文中隐式完成。
JLS 5.2 Assignment Conversion
Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of one of the following:
- a widening primitive conversion (§5.1.2)
- [...]
JLS 5.1.2 Widening Primitive Conversion
The following 19 specific conversions on primitive types are called the widening primitive conversions:
int
tolong
,float
, ordouble
- [...]
文字的其他数据类型后缀
如上所述,double
也有 D
或 d
后缀。例如考虑这个片段:
static void f(int i) {
System.out.println("(int)");
}
static void f(double d) {
System.out.println("(double)");
}
//...
f(1); // prints "(int)"
f(1D); // prints "(double)"
long
文字还有一个后缀,即L
或l
(小写字母)。 强烈建议您使用大写变体。
JLS 3.10.1 Integer Literals
An integer literal is of type
long
if it is suffixed with an ASCII letterL
orl
(ell
); otherwise it is of typeint
. The suffixL
is preferred, because the letterl
(ell
) is often hard to distinguish from the digit1
(one
).
关于java - 在 Java 中表示浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3033137/