問題描述
我有一個非常奇怪的問題,如果我像這樣聲明一個 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
這篇關于前面為 0 的 C++ int 更改整個值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!