問題描述
看下面的三行代碼.
float f = 1;
float g = 1.1;
float h = 1.1f;
第二行有編譯錯誤,而其他行沒有編譯錯誤.第一行在沒有后綴 f 的情況下工作正常,第三行在后綴 f 下工作.這是為什么呢?
Second line has compilation errors, while the other lines do not have compilation errors. First line is working fine without suffix f and third line is working with suffix f. Why is this?
推薦答案
Java 中的浮點字面量默認是 double
值.
Floating point literals in Java is a double
value by default.
如果浮點文字以 ASCII 字母 F
或 f
為后綴,則為 float
類型;否則它的類型是 double
并且可以選擇以 ASCII 字母 D
或 d
為后綴.
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
.因此,您有兩種選擇:
You can't assign a double
value to a float
without an explicit narrowing conversion. You therefore have two options:
- 對于文字,使用后綴
f
或F
來表示float
值 - 對于非文字,使用顯式轉換
(float)
- For literals, use the suffix
f
orF
to denote afloat
value - For non-literals, use an explicit cast
(float)
后者的一個例子是:
double d = 1.1;
float f = (float) d; // compiles fine!
關于擴大轉化率
這樣編譯的原因:
On widening conversions
The reason why this compiles:
float f = 1;
是因為從 int
到 float
的擴大轉換可以在賦值的上下文中隱式完成.
is because the widening conversion from int
to float
can be done implicitly in the context of an assignment.
賦值轉換發生在將表達式的值賦值給變量時:必須將表達式的類型轉換為變量的類型.賦值上下文允許使用以下之一:
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:
- 擴大的原始轉換(§5.1.2)
- [...]
以下 19 種基本類型的特定轉換稱為加寬基本類型轉換:
The following 19 specific conversions on primitive types are called the widening primitive conversions:
int
到long
、float
或double
- [...]
文字的其他數據類型后綴
如上所述,double
也有 D
或 d
后綴.以這個片段為例:
Other data type suffix for literals
As mentioned above, there's also the D
or d
suffix for double
. Consider this snippet for example:
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
(小寫字母).強烈建議您使用大寫變體.
There's also a suffix for long
literals, which is L
or l
(lowercase letter). It is highly recommended that you use the uppercase variant.
如果整數文字以 ASCII 字母 L
或 l
(ell
long>);否則它是 int
類型.后綴 L
是首選,因為字母 l
(ell
) 通常很難與數字 1
區分開來(一個
).
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 中表示浮點值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!