当前面为 0 时,scanf 读取错误的整数
Scanf reads wrong integer when 0 in front
这是我的第一个问题,如有不妥请见谅。
我对编程很陌生,我遇到了一个问题,我无法在网上找到解决方案。当对整数使用 scanf
时,如果我的输入以一个或两个零开头,在某些情况下它会在其他系统(甚至不是二进制)中读取它。
例如,0020
会变成16
,0030
会变成24
,0100
会变成64
。
它似乎可以使用 8
的幂,并考虑最多 8
的数字(键入 0009
将导致它打印 0
然后 9
).
可能有一个我不知道的简单规则,如果答案很明显,我很抱歉。提前感谢任何回答的人!
scanf
的文档指出格式字符 i
...
i
Matches an optionally signed integer; the next pointer must be
a pointer to int. The integer is read in base 16 if it begins
with 0x or 0X, in base 8 if it begins with 0, and in base 10
otherwise. Only characters that correspond to the base are
used.
如果你想强制读取一个十进制整数然后使用格式说明符d
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
所以我想这就是你所拥有的:
int value;
int n = scanf( "%i", &value );
改成这样:
int value;
int n = scanf( "%d", &value );
流行的基数(基数 8、10 和 16)有不同的表示法。
Base 8:也称为八进制。当您在输入数字前放置 0 时,您将数字定义为基数 8。因此,当您输入 020
时,它被读取为 16
(十进制)。
基数 10:也称为十进制。你只需写一个你想输入的数字,没有任何前导 0
s。所以当你输入 20
时,它被读取为 20
.
Base 16:也称为十六进制。你在前面写一个 0x
。所以输入0x20
,十进制会存储为32
。
如果您使用 scanf()
读取数字,格式说明符为 %d
%i
,那么它读取的是八进制数,并且将其解释为整数。
这是我的第一个问题,如有不妥请见谅。
我对编程很陌生,我遇到了一个问题,我无法在网上找到解决方案。当对整数使用 scanf
时,如果我的输入以一个或两个零开头,在某些情况下它会在其他系统(甚至不是二进制)中读取它。
例如,0020
会变成16
,0030
会变成24
,0100
会变成64
。
它似乎可以使用 8
的幂,并考虑最多 8
的数字(键入 0009
将导致它打印 0
然后 9
).
可能有一个我不知道的简单规则,如果答案很明显,我很抱歉。提前感谢任何回答的人!
scanf
的文档指出格式字符 i
...
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
如果你想强制读取一个十进制整数然后使用格式说明符d
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
所以我想这就是你所拥有的:
int value;
int n = scanf( "%i", &value );
改成这样:
int value;
int n = scanf( "%d", &value );
流行的基数(基数 8、10 和 16)有不同的表示法。
Base 8:也称为八进制。当您在输入数字前放置 0 时,您将数字定义为基数 8。因此,当您输入 020
时,它被读取为 16
(十进制)。
基数 10:也称为十进制。你只需写一个你想输入的数字,没有任何前导 0
s。所以当你输入 20
时,它被读取为 20
.
Base 16:也称为十六进制。你在前面写一个 0x
。所以输入0x20
,十进制会存储为32
。
如果您使用 scanf()
读取数字,格式说明符为 %d
%i
,那么它读取的是八进制数,并且将其解释为整数。