C++ - Decimal to binary converting

后端 未结 29 3651
一向
一向 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:31

    #include "stdafx.h"
    #include
    #include
    #include
    
    using namespace std;
    
    int main() {
        // Initialize Variables
        double x;
        int xOct;
        int xHex;
    
        //Initialize a variable that stores the order if the numbers in binary/sexagesimal base
        vector rem;
    
        //Get Demical value
        cout << "Number (demical base): ";
        cin >> x;
    
        //Set the variables
        xOct = x;
        xHex = x;
    
        //Get the binary value
        for (int i = 0; x >= 1; i++) {
            rem.push_back(abs(remainder(x, 2)));
            x = floor(x / 2);
        }
    
        //Print binary value
        cout << "Binary: ";
        int n = rem.size();
        while (n > 0) {
            n--;
            cout << rem[n];
        } cout << endl;
    
        //Print octal base
        cout << oct << "Octal: " << xOct << endl;
    
        //Print hexademical base
        cout << hex << "Hexademical: " << xHex << endl;
    
        system("pause");
        return 0;
    }
    

提交回复
热议问题