Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c - printf with "%d" of numbers starting with 0 (ex "0102") giving unexpected answer (ex '"66")

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???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because when the first digit of a number (integer constant) is 0 (and second must not be x or X), 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 specifier

   printf("%o", n);  

6.4.4.1 Integer constants:

  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.

  2. 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 or 0X.

 0xf 0xff 0X5fff   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...