0是十进制文字还是八进制文字?

零永远是零,所以没关系。但是在最近与一位朋友的讨论中,他说八进制文字如今几乎没有使用。†然后我发现实际上我的代码中几乎所有整数文字都是八进制的,即0。


0根据C ++语法,八进制文字是否正确?标准怎么说?


†我知道的唯一真正用途是用于UNIX文件权限


波斯汪
浏览 793回答 3
3回答

凤凰求蛊

是的,0是C ++中的八进制文字。根据C ++标准:2.14.2整数文字[lex.icon]integer-literal:&nbsp;&nbsp;&nbsp; &nbsp; decimal-literal integer-suffixopt&nbsp;&nbsp;&nbsp; &nbsp; octal-literal integer-suffixopt&nbsp;&nbsp;&nbsp; &nbsp; hexadecimal-literal integer-suffixopt&nbsp;&nbsp;decimal-literal:&nbsp;&nbsp;&nbsp; &nbsp; nonzero-digit&nbsp;&nbsp;&nbsp; &nbsp; decimal-literal digit&nbsp;&nbsp;octal-literal:&nbsp;&nbsp;&nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<--------------------<Here>&nbsp; &nbsp; octal-literal octal-digit

守着一只汪

任何带前缀的整数值0都是八进制值。即:01是八进制数1,010是八进制数10,即十进制数8,而0是八进制数0(即十进制数,其他为0)。所以是的,“ 0”是八进制。那是@Als的答案中语法片段的简单英语翻译:-)一个整数前缀0x是没有前缀0。0x是一个明显不同的前缀。显然有些人无法做出这种区分。按照相同的标准,如果我们继续:&nbsp;integer-literal:&nbsp; &nbsp; &nbsp;decimal-literal integer-suffixopt&nbsp; &nbsp; &nbsp;octal-literal integer-suffixopt&nbsp; &nbsp; &nbsp;hexadecimal-literal integer-suffixopt&nbsp;decimal-literal:&nbsp; &nbsp; &nbsp;nonzero-digit&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<<<---- That's the case of no prefix.&nbsp; &nbsp; &nbsp;decimal-literal digit-separatoropt digit&nbsp;octal-literal:&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <<<---- '0' prefix defined here.&nbsp; &nbsp; &nbsp;octal-literal digit-separatoropt octal-digit <<<---- No 'x' or 'X' is&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; allowed here.&nbsp;hexadecimal-literal:&nbsp; &nbsp; &nbsp;0x hexadecimal-digit&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<<<---- '0x' prefix defined here&nbsp; &nbsp; &nbsp;0X hexadecimal-digit&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<<<---- And here.&nbsp; &nbsp; &nbsp;hexadecimal-literal digit-separatoropt hexadecimal-digit

侃侃尔雅

显然所有以零开头的整数文字都是八进制的。这意味着它也包括0。由于零为零,因此差异不大。但是不知道这个事实会伤害您。当我尝试编写将二进制数字转换为十进制和十六进制输出的程序时,我意识到了这一点。每当我给出从零开始的数字时,我都会得到错误的输出(例如012 = 10,而不是12)。很高兴知道这些信息,这样您就不会犯同样的错误。
打开App,查看更多内容
随时随地看视频慕课网APP