用printf的"%D"给人意想不到的答案从0开始(; 0102&QUOT EX&QUOT)的数字(例如'" 66 QUOT;) [英] printf with "%d" of numbers starting with 0 (ex "0102") giving unexpected answer (ex '"66")
问题描述
我用低于code在我的printf语句。
无效的主要()
{
INT N = 0102;
的printf(%d个,N);
}
此打印66答案。我也改变变量n的值012.它给出了答案10.请帮我对这种转换是如何完成的?
这是因为,当一个数字(整型常量)的第一个数字是 0
(和第二绝不能 X
或 X
),编译器间$ p $点它作为一个八进制数。用它打印%d个
会给你一个十进制值。结果
要打印八进制值,你应该使用%0
说明
的printf(%O,N);
6.4.4.1整型常量:
这是整型常量以数字开头,但没有时间或指数的一部分。它可具有preFIX指定其基部和指定其类型的后缀。
一个十进制常量开始非零数字和小数点组成的序列
数字。 八进制常量由preFIX 0任选随后的序列
数字0〜7只。十六进制常量由preFIX 0x或0X遵循
通过的十进制数字序列和值的字母(或A)到f(或F)
10至15元。
块引用>整型常量:
1 的常数:必须的不的开头
0
。12 125 3546
2 八常量:必须以
0
开始。012 0125 03546
3 十六进制常量:总是以
0X
开始或0X
。0xF的0xFF的0X5fff
I used below code in my printf statement.
void main() { int n=0102; printf("%d", n); }
This prints 66 as the answer. I also changed the value of variable n to 012. It gives the answer 10. Please help me regarding how this conversion is done???
解决方案This is because when the first digit of a number (integer constant) is
0
(and second must not bex
orX
), the compiler interprets it as an octal number. Printing it with%d
will give you a decimal value.
To print octal value you should use%o
specifierprintf("%o", n);
6.4.4.1 Integer constants:
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.
Integer Constants:
1.Decimal constants: Must not begins with
0
.12 125 3546
2.Octal Constants: Must begins with a
0
.012 0125 03546
3.Hexadecimal Constants: always begins with
0x
or0X
.0xf 0xff 0X5fff
这篇关于用printf的"%D"给人意想不到的答案从0开始(; 0102&QUOT EX&QUOT)的数字(例如'" 66 QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!