具有前面的0的C ++ int更改整个值 [英] C++ int with preceding 0 changes entire value
问题描述
我有这个很奇怪的问题,如果我声明一个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
?
如果你对变量名进行破解猜测我试图做操作。
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
等于 code>。
that is equal to 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
这篇关于具有前面的0的C ++ int更改整个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!