是否可以同时使用L和E字母来初始化'Long'数字文字?

问题描述 投票:0回答:1

如果我将long变量声明为:

long n = 1E+12L;

编译器抛出语法错误。

并且当我声明为:

long n = 1E+12;

引发不兼容的类型错误。

另一方面,很高兴在浮点数和双打中接受两个字母:

double n = 1E+12D;
float n = 1E+12F;

为什么它不适用于long文字?我是否必须每次都删除L字母并将其转换为long

java literals
1个回答
0
投票

不,这是不可能的。 Java语言规范e中不允许在数字文字(即E)中使用scientific notationinteger literals

IntegerLiteral:
  DecimalIntegerLiteral
  HexIntegerLiteral
  OctalIntegerLiteral
  BinaryIntegerLiteral

DecimalIntegerLiteral:
  DecimalNumeral [IntegerTypeSuffix]

...

IntegerTypeSuffix:
  (one of)
  l L

floating-point literals允许,但是不能有lL后缀:

FloatingPointLiteral:
  DecimalFloatingPointLiteral
  HexadecimalFloatingPointLiteral

DecimalFloatingPointLiteral:
  Digits . [Digits] [ExponentPart] [FloatTypeSuffix]
  . Digits [ExponentPart] [FloatTypeSuffix]
  Digits ExponentPart [FloatTypeSuffix]
  Digits [ExponentPart] FloatTypeSuffix

ExponentPart:
  ExponentIndicator SignedInteger

ExponentIndicator:
  (one of)
  e E

...

因此,您必须完整写出long文字。但是,为方便起见,您可以使用下划线将数字分组,例如1_000_000_000_000L,以使零数清晰可见。

© www.soinside.com 2019 - 2024. All rights reserved.