我的代碼是這樣的 -爲什麼INT /字節/短/長轉換爲浮動/雙無類型轉換,但反之亦然不可能
public void abc{
long a=1111;
float b=a; // this works fine even though this is narrowing conversion
long c=b;// this gives compilation error
}
你能解釋一下爲什麼會這樣?
我的代碼是這樣的 -爲什麼INT /字節/短/長轉換爲浮動/雙無類型轉換,但反之亦然不可能
public void abc{
long a=1111;
float b=a; // this works fine even though this is narrowing conversion
long c=b;// this gives compilation error
}
你能解釋一下爲什麼會這樣?
的原因是JLS 5.1.2規定: 它說:長浮動或雙是擴大轉換。
然而,浮子字節,短,字符型,整型,或長正在縮小轉換。
這就是爲什麼
float b=a;
工作正常,在你的程序,因爲它是擴大轉換。
而 long c=b;
是顯示編譯錯誤,因爲它是一個收縮轉換。
轉換規則是基於數字數據類型可以表示的範圍內。通過long
允許的範圍包含在由float
允許的範圍,因此隱式轉換是允許的,儘管精度明顯損失:長存儲64個比特,而浮只有32,因此轉換扔掉的數據的一半。
當您從整數類型轉換爲浮點類型時,始終清楚您想要執行的操作:更改數字的表示形式,但保留相同的數字。
另一方面,從浮點到整數類型的轉換有一些不明確之處:不清楚你想要用小數部分做什麼。你可能想
這就是爲什麼語言要求您具體說明將浮點數轉換爲整數類型時要執行的操作。
I Java允許隱式擴展轉換,但不能縮小範圍。這基本上意味着可以轉換爲任何可以保存原始數據類型的大或大值的數據類型,而無需顯式轉換數據。但是這意味着你可能會失去精確度。
ex。
long original = Long.MAX_VALUE-1;
float f = original;
long result = (long) f;
System.err.println(original);
System.err.println(f);
System.err.println(result);
看看這個
byte
1 signed byte (two's complement). Covers values from -128 to 127.
short
2 bytes, signed (two's complement), -32,768 to 32,767
int
4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.
Like all numeric types ints may be cast into other numeric types
(byte, short, long, float, double). When lossy casts are done (e.g.
int to byte) the conversion is done modulo the length of the smaller
type.
long
8 bytes signed (two's complement). Ranges from
-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
float
4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45
to 3.40282346638528860e+38 (positive or negative).
Like all numeric types floats may be cast into other numeric types
(byte, short, long, int, double). When lossy casts to integer types
are done (e.g. float to short) the fractional part is truncated and
the conversion is done modulo the length of the smaller type.
double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d
to 1.79769313486231570e+308d (positive or negative).
現在你可以明白,如果我們要代表其他一些float和double值。部分原始數字(float或double)將會丟失。所以鑄造是不可能在這種情況下
從64位「長」值變爲32位「浮點」值時,部分數字也會丟失,所以聽起來並不令人信服。 – Joni
希望這有助於 http://stackoverflow.com/questions/1293819/why-does-java-implicitly-without-cast-convert-a-long-to- a-float – Kaushal