【问题标题】:Why does casting infinity into byte or short equal -1 in Java? [duplicate]为什么在Java中将无穷大转换为字节或短等于-1? [复制]
【发布时间】:2018-11-20 14:30:18
【问题描述】:

最近我发现,如果你取一个 double 或 float 并除以 0,你会得到无穷大的值。我将无穷大转换为每种数据类型(通过编写(byte)variable(short)variable 等),我发现如果将其转换为字节或短,它会给出值 -1,但如果将其转换为任何其他数据类型,它会给出你把它的最大值回来。我想知道为什么会这样。有人猜到了吗?

这是我用来测试它的代码。

double dsa = 1.00 / 0;

System.out.println("Byte");
System.out.println((byte)dsa);
System.out.println(Byte.MAX_VALUE + "\n");

System.out.println("Short");
System.out.println((short)dsa);
System.out.println(Short.MAX_VALUE + "\n");

System.out.println("Integer");
System.out.println((int)dsa);
System.out.println(Integer.MAX_VALUE + "\n");

System.out.println("Long");
System.out.println((long)dsa);
System.out.println(Long.MAX_VALUE + "\n");

System.out.println("Float");
System.out.println((float)dsa);
System.out.println(Float.MAX_VALUE + "\n");

System.out.println("Double");
System.out.println((double)dsa);
System.out.println(Double.MAX_VALUE + "\n");

这是控制台给我的:

Byte
-1
127

Short
-1
32767

Integer
2147483647
2147483647

Long
9223372036854775807
9223372036854775807

Float
Infinity
3.4028235E38

Double
Infinity
1.7976931348623157E308

【问题讨论】:

  • “我转换了无穷大” - 我们可以看看你的代码吗?
  • 您的意思是“casted”而不是“converted”吗?
  • 我向其中添加了代码,我的意思可能是强制转换。抱歉,我不会用英语学习编程,所以我不确定。看看代码就行了。

标签: java type-conversion byte short infinity


【解决方案1】:

因为正无穷大定义为0x7ff0000000000000。来自Double类源码:

/**
 * A constant holding the positive infinity of type
 * {@code double}. It is equal to the value returned by
 * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
 */
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

另外请注意,casting 不是 converting

【讨论】:

  • 很抱歉,如果这听起来对你来说很愚蠢,但为什么 0x7ff0000000000000 以字节或短形式给出 -1 而在其他类型中给出最大值?
  • 对不起,我的错,我以某种方式读到 0 而不是 -1:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多