简体   繁体   English

浮点字面值中“0”作为前缀的含义是什么?

[英]What's the meaning of “0” as prefix in a floating point literal?

Using "0" (zero) as a prefix in an integer literal changes its base to octal. 使用“0”(零)作为整数文字中的前缀会将其基数更改为八进制。 This is why 这就是为什么

System.out.println(010);

will print 8 . 将打印8 But using "F" as a suffix 但使用“F”作为后缀

System.out.println(010F);

will make it float losing octal base (going back to decimal) and will print 10.0 . 将使它浮动失去八进制基数(返回到十进制)并将打印10.0

Is there any difference between 010F and 10F ? 010F10F之间有什么区别吗? Has the "0" prefix any kind of meaning when working with floats? 使用浮动时,“0”前缀是否有任何意义?

From the Java Language Specification, on Floating Point literals 从Java语言规范, 浮点文字

FloatingPointLiteral: FloatingPointLiteral:

  • DecimalFloatingPointLiteral DecimalFloatingPointLiteral
  • HexadecimalFloatingPointLiteral HexadecimalFloatingPointLiteral

DecimalFloatingPointLiteral: DecimalFloatingPointLiteral:

  • Digits . 数字 [Digits] [ExponentPart] [FloatTypeSuffix] [数字] [ExponentPart] [FloatTypeSuffix]
  • . Digits [ExponentPart] [FloatTypeSuffix] 数字[ExponentPart] [FloatTypeSuffix]
  • Digits ExponentPart [FloatTypeSuffix] Digits ExponentPart [FloatTypeSuffix]
  • Digits [ExponentPart] FloatTypeSuffix 数字[ExponentPart] FloatTypeSuffix

where Digits Digits

Digits: 数字:

  • Digit 数字
  • Digit [DigitsAndUnderscores] Digit 数字 [DigitsAndUnderscores] 数字

Digit: 数字:

  • 0 0
  • NonZeroDigit NonZeroDigit

DigitsAndUnderscores: DigitsAndUnderscores:

  • DigitOrUnderscore {DigitOrUnderscore} DigitOrUnderscore {DigitOrUnderscore}

DigitOrUnderscore: DigitOrUnderscore:

  • Digit 数字
  • _ _

Underscores: 强调:

  • _ {_} _ {_}

You can have any number of leading 0 for floating point literals. 浮点文字可以包含任意数量的前导0

I cannot find anything in the JLS that explains why this is allowed, but I can imagine it simplifies parsing. 我在JLS中找不到任何解释为什么允许这样做的东西,但我可以想象它简化了解析。

Octal notation is only used for integers, not for floating point numbers. 八进制表示法仅用于整数,不用于浮点数。 This is not specific to Java. 这不是Java特有的。 So the extra 0 has no effect (other than being confusing for the human reader). 所以额外的0没有效果(除了让人类读者感到困惑)。

Only Integer Literals can be represented in Octal form(Base-8) in Java. 只有整数文字可以用Java的八进制形式(Base-8)表示。

jls-3.10.1 : Integer Literals jls-3.10.1:整数文字

Floating point numbers can be represented either in Decimal (or) Hexadecimal form only. 浮点数可以仅以十进制(或)十六进制形式表示。

jls-3.10.2 : Floating Literals jls-3.10.2:浮动文字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM