天天看点

C语言,进制转换之二进制转十进制,完整代码

#include "iostream"
using namespace std;
#define MAX 50
int main()//二转十
{
    cout << "请输入二进制数,并以‘$’结束:";
    char elem2[MAX];
    int flag = ;
    char ch;
    int i = ;
    while (flag)
    {
        cin >> ch;
        if (ch != '$')
        {
            elem2[i] = ch;
            i++;
        }
        else
        {
            flag = ;
        }
    }
    int length = i;
    int n = ;
    int sum = ; 
    int product = ;
    for (n = ; n < length; n++)//判断是否是二进制数
    {
        if ('1' == elem2[n] || '0' == elem2[n])
            sum++;
    }
    if (sum == length)
    {
        int m = ;
        int p = ;
        int q = ;
        for (m = length - ; m >= ; m--)
        {
            q = elem2[m] - '0';
            product += q * pow(, p);
            p++;
        }
        cout << "对应的十进制数是:"<<product<<endl;
    }
    else
    {
        cout << "你输入的不是二进制数!"<<endl;
    }
    return ;
}
           

继续阅读