C++ - Decimal to binary converting

后端 未结 29 3650
一向
一向 2020-11-28 18:53

I wrote a \'simple\' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there\'s a lot simpler way so can you show me? Here\'s the code:<

29条回答
  •  甜味超标
    2020-11-28 19:43

    DECIMAL TO BINARY NO ARRAYS USED *made by Oya:

    I'm still a beginner, so this code will only use loops and variables xD...

    Hope you like it. This can probably be made simpler than it is...

        #include 
        #include 
        #include 
    
        using namespace std;
    
        int main()
        {
            int i;
            int expoentes; //the sequence > pow(2,i) or 2^i
            int decimal; 
            int extra; //this will be used to add some 0s between the 1s
            int x = 1;
    
            cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
            cout << "\n\nWARNING: Only works until ~1.073 millions\n";
            cout << "     To exit, enter a negative number\n\n";
    
            while(decimal >= 0){
                cout << "\n----- // -----\n\n";
                cin >> decimal;
                cout << "\n";
    
                if(decimal == 0){
                    cout << "0";
                }
                while(decimal >= 1){
                    i = 0;
                    expoentes = 1;
                    while(decimal >= expoentes){
                        i++;
                        expoentes = pow(2,i);
                    }
                    x = 1;
                    cout << "1";
                    decimal -= pow(2,i-x);
                    extra = pow(2,i-1-x);
                    while(decimal < extra){
                        cout << "0";
                        x++;
                        extra = pow(2,i-1-x);
                    }
                }
            }
            return 0;
        }
    

提交回复
热议问题