我在 printf 语句中使用了以下代码。
void main()
{
int n=0102;
printf("%d", n);
}
这将打印 66 作为答案。我还将变量 n 的值更改为 012。它给出了答案 10。请帮助我了解此转换是如何完成的???
最佳答案
这是因为当数字(整数常量)的第一位是 0
(第二位不能是 x
或 X
) ,编译器将其解释为八进制数。用 %d
打印它会给你一个十进制值。
要打印八进制值,您应该使用 %o
说明符
printf("%o", n);
6.4.4.1 整型常量:
An integer constant begins with a digit, but has no period or exponent part. It may have a prefix that specifies its base and a suffix that specifies its type.
A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits. An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and the letters a (or A) through f (or F) with values 10 through 15 respectively.
整数常量:
1.十进制常量:必须不以0
开头。
12 125 3546
2.八进制常数:必须以0
开头。
012 0125 03546
3.十六进制常量:总是以0x
或0X
开头。
0xf 0xff 0X5fff
关于c - 带有 "%d"以 0 开头的数字(例如 "0102")的 printf 给出意外的答案(例如 '"66"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19652583/