首页 > 解决方案 > Eclipse 中的双精度浮点数与双精度浮点数

问题描述

我的问题分为两部分。

  1. 为什么以下在 Eclipse 中可以正常工作?“双”不是一堂课吗?
    Double h = 2.5;
    double j = 2;
  1. 为什么上面的“Double”在我不为其分配十进制值时会给我一个错误,但“double”无论我是否为其分配一个十进制值都可以?

标签: javaeclipsedouble

解决方案


如前所述,该术语是自动装箱。原始类型的对象包装器将自动转换。

至于你的第二部分,

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 float从or转换时不需要强制转换long 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);
            }
        }

推荐阅读