簡體   English   中英

為什么int / byte / short / long可以在沒有類型轉換的情況下轉換為float / double,反之亦然

[英]Why can int/byte/short/long be converted to float/double without typecasting but vice-versa not possible

我的代碼是這樣的 -

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中指定:它表示: long to float或double是一個擴展轉換。
float,byte,short,char,int或long縮小了轉換。
這就是為什么
float b=a; 在你的程序中運行正常,因為它正在擴大轉換。
long c=b; 顯示編譯錯誤,因為它是一個縮小的轉換。

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

另一方面,從浮點轉換為整數類型有一些模糊性:不清楚您想對小數部分做什么。 你可能想要

  • 截斷小數部分,
  • 執行數學舍入,或
  • 將數字向上舍入。

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

因為long可以表示為float ,但任何float都不能表示為long 這是數學而不是Java。

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

long c = (long) b;

轉換規則基於數據類型可以表示的數字范圍。 long允許的范圍包含在float允許的范圍內,因此盡管明顯損失了精度,仍允許隱式轉換:long存儲64位而float只有32,因此轉換會丟棄一半的數據。

我允許Java隱式擴展轉換,但不允許縮小。 這基本上意味着可以轉換為任何數據類型,該數據類型可以保存原始數據類型的大或大值,而無需顯式地轉換數據。 但這確實意味着您可能會失去精確度。

恩。

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。 擴大原始轉換

看看這個

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

現在你可以意識到我們是否要在其他人中代表一些浮點值和雙值。 原始數字(浮點數或雙數)的一部分將丟失。 所以在這種情況下不可能進行鑄造

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM