简体   繁体   中英

Confusion with literals, arithmetic in C

I wrote the following code with an expectation that it output 211 , but when I compile and run it, I see 137 .

Could someone please explain what's going on? Thanks.

‎#include <stdio.h>

int main()
{
    int binary1,binary2;

    binary1 = 0100;
    binary2 = 0111;

    printf("%d\n", binary1 + binary2);

    return 0:
}

These are not binary numbers but octal (base 8):

binary1 = 0100; // = 64
binary2 = 0111; // = 64 + 8 + 1 = 73

printf("%d \n", binary1 + binary2); // = 64 + 73 = 137

Because %d prints out the numbers in decimal. If you want to print octal numbers, you would need to use %o , which would print out 211 .

  • %d : decimal => 137
  • %o : octal => 211

printf() does not know you defined the numbers in octal.

The leading zeroes in 0100 and 0111 means the numbers are to be interpreted as octal numbers. 100 in octal is 64 in decimal and 111 in octal is 73 in decimal.

两个数字都是八进制的,并将它们添加到基数8中。

In C a numeric literal prefixed with a '0' is octal (base 8). That why it is displaying the result 137

0100 in octal is equivalent to 64 in decimal and 0111 is to 73,

so 64+73 = 137

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM