2013-06-30 80 views

回答

8

的原因是JLS 5.1.2規定: 它說:長浮動或雙是擴大轉換。
然而,浮子字節,短,字符型,整型,或長正在縮小轉換。
這就是爲什麼
float b=a;工作正常,在你的程序,因爲它是擴大轉換。
long c=b;是顯示編譯錯誤,因爲它是一個收縮轉換。

2

由於long可以被表示爲一個float,但任何float不能被表示爲long。這不是Java的數學。

在這裏,你可以添加一個投來強制編譯。當然,由於您將float轉換爲long,因此可能會失去精度。

long c = (long) b; 
+0

「長時間可以表示爲浮動」< - 好吧,如果長整數值的幅度足夠大,則不是這樣... – fge

+0

@fge沒錯。感謝您的評論。 – LaurentG

+0

你可以這樣寫:每一個長的值都可以用一個浮點數**近似**,反之亦然。 – Ingo

0

轉換規則是基於數字數據類型可以表示的範圍內。通過long允許的範圍包含在由float允許的範圍,因此隱式轉換是允許的,儘管精度明顯損失:長存儲64個比特,而浮只有32,因此轉換扔掉的數據的一半。

7

當您從整數類型轉換爲浮點類型時,始終清楚您想要執行的操作:更改數字的表示形式,但保留相同的數字。

另一方面,從浮點到整數類型的轉換有一些不明確之處:不清楚你想要用小數部分做什麼。你可能想

  • 截斷小數部分,
  • 進行數學舍入,或
  • 回合數最多。

這就是爲什麼語言要求您具體說明將浮點數轉換爲整數類型時要執行的操作。

0

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); 

多見於JLS 5.1.2. Widening Primitive Conversion

0

看看這個

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)將會丟失。所以鑄造是不可能在這種情況下

+0

從64位「長」值變爲32位「浮點」值時,部分數字也會丟失,所以聽起來並不令人信服。 – Joni

相關問題