【问题标题】:Why printf output of the variable is different为什么变量的printf输出不同
【发布时间】:2012-11-10 10:32:30
【问题描述】:

我不知道为什么会这样!想知道原因。

{
int i=01;
printf("%d\n",i);
}
output: 1

但是

{
int i=011;
printf("%d\n",i);
}
output: 9

有人知道答案吗?

【问题讨论】:

    标签: c printf


    【解决方案1】:

    011 是一个八进制常数。 11 (b8) = 9 (b10).

    C11 (n1570),第 6.4.4.1 节整数常量
    八进制常数由前缀 0 组成,可选地后跟数字 0 到 7 的序列。

    【讨论】:

    • 为什么它会打印八进制数,因为我给出了一个十进制整数值!
    • 因为您的数字常量以 0 开头。阅读报价。
    • @Iqbal 是的,当然,1*8 + 2*1 = 10。如果您的文字以 0 开头,则它是八进制文字。尝试在printf 中使用%o 格式。
    • 阅读引号 ;) 前缀 0 表示八进制常量(基数为 8)(前缀 0x 或 0X 或简单的 x 或 X 表示十六进制基数 16)
    【解决方案2】:

    011 = 八进制,(1*8)+1=9 ....................................

    【讨论】:

      【解决方案3】:
      The numbers which are preceded by 0 is called octal numbers in c programming .
      to evaluate such an expression we simply follow a conversion rule of converting octal to decimal number system
      For conversion the following steps are  to be proceed
      such as 011
      here 0 indicate the number is octal 
      and we are require to convert 11 which is (base 8) to decimal (base 10)
      
      11= 1x8^1+1x8^0
         =8+1
         =9
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        • 2023-01-02
        • 2019-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多