前面为 0 的 C++ int 更改整个值

2021-12-13 00:00:00 variables c++

我有一个非常奇怪的问题,如果我像这样声明一个 int

I have this very strange problem where if I declare an int like so

int time = 0110;

然后显示到控制台返回的值为72.但是,当我删除前面的 0 以便 int time = 110; 控制台然后像预期的那样显示 110 .

and then display it to the console the value returned is 72. However when I remove the 0 at the front so that int time = 110; the console then displays 110 like expected.

我想知道两件事,首先为什么它在 int 的开头使用前面的 0 来执行此操作,并且有没有办法阻止它,以便 0110 至少等于110?
其次,有没有什么办法可以让0110返回0110?
如果您对变量名称进行猜测,我会尝试在 24 小时内进行操作,但此时 1000 之前的任何时间都会因此导致问题.

Two things I'd like to know, first of all why it does this with a preceding 0 at the start of the int and is there a way to stop it so that 0110 at least equals 110?
Secondly is there any way to keep it so that 0110 returns 0110?
If you take a crack guess at the variable name I'm trying to do operations with 24hr time, but at this point any time before 1000 is causing problems because of this.

提前致谢!

推荐答案

从 0 开始的整数字面量定义了八进制整数字面量.现在在 C++ 中有四类整数文字

An integer literal that starts from 0 defines an octal integer literal. Now in C++ there are four categories of integer literals

integer-literal:
    decimal-literal integer-suffixopt
    octal-literal integer-suffixopt
    hexadecimal-literal integer-suffixopt
    binary-literal integer-suffixopt

八进制整数字面量定义如下

And octal-integer literal is defined the following way

octal-literal:
    0 octal-literal
    opt octal-digit

就是从0开始.

因此这个八进制整数文字

Thus this octal integer literal

0110

对应下面的十进制数

8^2 + 8^1 

即等于 72.

您可以通过运行以下简单程序来确定八进制表示中的 72 等于 110

You can be sure that 72 in octal representation is equivalent to 110 by running the following simple program

#include <iostream>
#include <iomanip>

int main() 
{
    std::cout << std::oct << 72 << std::endl;

    return 0;
}

输出是

110

相关文章