具體程式碼如下
#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;
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"<<elem8[j]<<" ";
cout << "你輸入的不是二進位制數!" << endl;
return 0;
具體程式碼如下
#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"<<elem8[j]<<" ";
cout << endl;
}
else
{
cout << "你輸入的不是二進位制數!" << endl;
}
return 0;
}