用printf的"%D"给人意想不到的答案从0开始(; 0102&QUOT EX&QUOT)的数字(例如'" 66 QUOT;) [英] printf with "%d" of numbers starting with 0 (ex "0102") giving unexpected answer (ex '"66")

查看:297
本文介绍了用printf的"%D"给人意想不到的答案从0开始(; 0102&QUOT EX&QUOT)的数字(例如'" 66 QUOT;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用低于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整型常量:


  

      
  1. 这是整型常量以数字开头,但没有时间或指数的一部分。它可具有preFIX指定其基部和指定其类型的后缀。


  2.   
  3. 一个十进制常量开始非零数字和小数点组成的序列
      数字。 八进制常量由preFIX 0任选随后的序列
      数字0〜7只
    。十六进制常量由preFIX 0x或0X遵循
      通过的十进制数字序列和值的字母(或A)到f(或F)
      10至15元。


  4.   


整型常量:

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

这篇关于用printf的"%D"给人意想不到的答案从0开始(; 0102&QUOT EX&QUOT)的数字(例如'" 66 QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆