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

#include "iostream"
using namespace std;
#define MAX 50
int main()//二转八
{
    cout << "请输入二进制数,并以‘$’结束:";
    char elem2[MAX];
    int flag = 1;
    char ch;
    int i = 0;
    while (flag)
    {
        cin >> ch;
        if (ch != '$')
        {
            elem2[i] = ch;
            i++;
        }
        else
        {
            flag = 0;
        }
    }
    int length = i;
    int n = 0;
    int sum = 0;
    int product = 0;
    if (length % 3 != 0)//将缺位的二进制码用0补齐
    {
        int n = 3 - length % 3;
        int i = 0;
        for (i = length-1; i>=0; i--)
            elem2[i + n] = elem2[i];
        length += n;
        for (i = 0; i < n; i++)
            elem2[i] = '0';
        cout << "补齐之后的内容是:" << endl;
        for (i = 0; i < length; i++)
            cout << elem2[i] << " ";
        cout << endl;
    }
    for (n = 0; n < length; n++)//判断是否是二进制数
    {
        if ('1' == elem2[n] || '0' == elem2[n])
            sum++;
    }
    if (sum == length)
    {
        int elem8[MAX];
        int r = 0;
        int m = 0;
        int p = 0;
        int q = 0;
        for (m = length - 1; m >= 0; m--)
        {
            q = elem2[m] - '0';
            product += q * pow(2, p);
            p++;
            if (3 == p)
            {
                elem8[r] = product;
                r++;
                p = 0;
                product = 0;
            }
        }
        int j = 0;
        cout << "对应的八进制数是:" << endl;
        for (j = r-1; j>=0;j--)
        cout<<"0"<" ";
        cout << endl;

    }
    else
    {
        cout << "你输入的不是二进制数!" << endl;
    }
    return 0;
}

你可能感兴趣的:(c)