簡體   English   中英

double 與 Double 作為 Eclipse 中的浮點數

[英]double vs Double as Floating Point Numbers in Eclipse

我的問題分為兩部分。

  1. 為什么以下在 Eclipse 中可以正常工作? “雙”不是 class 嗎?
    Double h = 2.5;
    double j = 2;
  1. 為什么上面的“Double”在我不為其分配十進制值時會給我一個錯誤,但“double”無論我是否為其分配一個十進制值都可以?

如前所述,該術語是自動裝箱。 原始類型的 object 包裝器將自動轉換。

至於你的第二部分,

Double a = 2;

不起作用,因為 2 不是雙精度數,並且自動裝箱僅適用於相同類型。 在這種情況下, 2是一個 int。

但如果你投它。

Double a = (double)2;

工作得很好。

double a = 2;

之所以有效,是因為 int 可以自動轉換為 double。 但走另一條路是行不通的。

int a = 2.2; // not permitted.

查看 轉換部分 在 Java 語言規范中。 警告有時可能難以閱讀。

修正答案。

在 java 中,您可以向上或向下投射或縮小或擴大投射(從 32 位到 16 位)值正在縮小。 但我傾向於認為這是losing vs not losing的東西。 在大多數情況下,如果您有可能在分配中失去部分價值,您需要進行轉換,否則您不需要(參見最后的例外情況)。 這里有些例子。

long a = 2; // 2 is an integer but going to a long doesn't `lose` precision.
int b = 2L; // here, 2 is a long and the assignment is not permitted.  Even 
            // though a long 2 will fit inside an int, the cast is still 
            // required.
int b = (int)2L;  // Fine, but clearly a contrived case

浮點數也一樣。

float a = 2.2f; // fine
double b = a;   // no problem, not precision lost
float c = b;    // can't do it, as it requires a cast.

double c = 2.2f; // a float to a double, again a not problem.
float d = 2.2;  // 2.2 is a double by default so requires a cast or the float designator.
float d = (float)2.2;

例外

int to floatlong to double時不需要強制轉換。 但是,精度仍然會丟失,因為浮點數只有24位精度,而雙精度數只有53位。

要查看ints ,您可以運行以下命令:

        for (int i = Integer.MAX_VALUE; i > Integer.MAX_VALUE-100; i--) {
            float s = i;
            int t = (int)s; // normal cast required
            if (i != t) {
                System.out.println (i + " " + t);
            }
        }

Double 是一個包裝器 class,創建一個新的 Double 將 SAME 類型的原始變量轉換為 Object。 對於Double h = 2 ,您將int包裝到 Double 中。 由於包裝僅適用於相同類型,如果您希望Double變量為 2,那么您應該使用

Double h = 2.0;

暫無
暫無

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

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