您的位置:澳门402永利com > 澳门402永利com网络 > C语言二进制转十进制代码

C语言二进制转十进制代码

发布时间:2019-09-24 15:54编辑:澳门402永利com网络浏览(162)

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    unsigned int pow(unsigned int a, unsigned int n);
    
    int main()
    {
        string binary;
        unsigned int decimal = 0;
    
        cout << "Enter a binary number: ";
        cin >> binary;
    
        for(int i = binary.length()-1; i >= 0; i--) {
            if(binary[i] > '1' || binary[i] < '0') {
                cout << "Invalid binary number!" << endl;
                return 1;
            } else {
                decimal += (binary[i] - '0') * pow(2, (binary.length()-i-1));
            }
        }
    
        cout << "Decimal: " << decimal << endl; 
        return 0;
    }
    
    unsigned int pow(unsigned int a, unsigned int n)
    {
        unsigned int r = 1;
        while( n-- > 0 ) r *= a;
        return r;
    }
    

    本文由澳门402永利com发布于澳门402永利com网络,转载请注明出处:C语言二进制转十进制代码

    关键词:

上一篇:没有了

下一篇:没有了