C++ int with preceding 0 changes entire value

后端 未结 4 814
春和景丽
春和景丽 2020-11-30 15:49

I have this very strange problem where if I declare an int like so

int time = 0110;

and then display it to the console the value returned i

相关标签:
4条回答
  • 2020-11-30 15:53

    Zero at the start means the number is in octal. Without it is decimal.

    0 讨论(0)
  • 2020-11-30 15:54

    An integer literal that starts from 0 defines an octal integer literal. Now in C++ there are four categories of integer literals

    integer-literal:
        decimal-literal integer-suffixopt
        octal-literal integer-suffixopt
        hexadecimal-literal integer-suffixopt
        binary-literal integer-suffixopt
    

    And octal-integer literal is defined the following way

    octal-literal:
        0 octal-literal
        opt octal-digit
    

    That is it starts from 0.

    Thus this octal integer literal

    0110
    

    corresponds to the following decimal number

    8^2 + 8^1 
    

    that is equal to 72.

    You can be sure that 72 in octal representation is equivalent to 110 by running the following simple program

    #include <iostream>
    #include <iomanip>
    
    int main() 
    {
        std::cout << std::oct << 72 << std::endl;
    
        return 0;
    }
    

    The output is

    110
    
    0 讨论(0)
  • 2020-11-30 16:07

    The compiler is interpreting the leading zero as an octal number. The octal value of "110" is 72 in decimal. There's no need for the leading zero if you're just storing an int value.

    You're trying to store "time" as it appears on a clock. That's actually more complicated than a simple int. You could store the number of minutes since midnight instead.

    0 讨论(0)
  • 2020-11-30 16:13

    It is because of Integer Literals. Placing a 0 before number means its a octal number. For binary it is 0b, for hexadecimal it is 0x or 0X. You don't need to write any thing for decimal. See the code bellow.

    #include<stdio.h>
    
    int main()
    {
        int binary = 0b10;
        int octal=010;
        int decimal = 10;
        int hexa = 0x10;
        printf("%d %d %d %d\n", octal, decimal, hexa, binary);
    }
    

    For more information visit tutorialspoint.

    0 讨论(0)
提交回复
热议问题