printf with “%d” of numbers starting with 0 (ex “0102”) giving unexpected answer (ex '“66”)

浪子不回头ぞ 提交于 2019-11-26 11:40:37

问题


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


回答1:


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   



回答2:


You tell printf to print the value in decimal (%d). Use %o to print it in octal.




回答3:


any numeric literal starting with 0 followed only by numbers is taken as an octal number. Hence

0102 = (1 * 8^2) + (0  * 8^1) + (2 * 8^0)  = 64 + 0 + 2 = 66
012 = (1 * 8^1) + (2 * 8^0) = 8 + 2 = 10


来源:https://stackoverflow.com/questions/19652583/printf-with-d-of-numbers-starting-with-0-ex-0102-giving-unexpected-answer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!