为什么 Java 中的十六进制实数需要指数

Why are exponents required for hex real numbers in Java

例如,在 Java 中,这是一个十六进制数 0x10

0x10.2P2 是正确的十六进制双精度数。

但是为什么0x1f.2不正确呢?为什么我们不能使用它,虽然 0x1f.2P1 应该给出相同的结果但它有效?

好吧,如果您的意思是 why,我们将不得不希望负责语法的人中的一位能插话。在我看来,好像使指数成为可选的不会损害解析文字的能力,但我没有详细考虑过。我所能提供的是 Java Language Specification §3.10.2 需要它:

For hexadecimal floating-point literals, at least one digit is required (in either the whole number or the fraction part), and the exponent is mandatory, and the float type suffix is optional. The exponent is indicated by the ASCII letter p or P followed by an optionally signed integer.

在之前的 Stack Overflow 问题中有一些 "why" 的衡量标准:

0xp0 prints 0.0 (Hexadecimal Floating Point Literal)

这里:

P in constant declaration

来自@NPE 的 "best answer" 给出了一个理由:

At first glance it might seem that the 0x prefix is sufficient to identify a hex floating-point literal, so why have the Java designers chosen to change the letter from e to p? This has to do with e being a valid hex digit, so keeping it would give rise to parsing ambiguity. Consider:

0x1e+2

Is that a hex double or the sum of two integers, 0x1e and 2? When we change e to p, the ambiguity is resolved:

0x1p+2