📅  最后修改于: 2020-09-25 06:22:05             🧑  作者: Mango
在此程序中,我们将首先将二进制数字转换为十进制。然后,十进制数字转换为八进制。
#include
#include
using namespace std;
int convertBinarytoOctal(long long);
int main()
{
long long binaryNumber;
cout << "Enter a binary number: ";
cin >> binaryNumber;
cout << binaryNumber << " in binary = " << convertBinarytoOctal(binaryNumber) << " in octal ";
return 0;
}
int convertBinarytoOctal(long long binaryNumber)
{
int octalNumber = 0, decimalNumber = 0, i = 0;
while(binaryNumber != 0)
{
decimalNumber += (binaryNumber%10) * pow(2,i);
++i;
binaryNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
输出
Enter a binary number: 10001
10001 in binary = 21 in octal
用户输入的二进制数将传递给convertBinaryToOctal()
函数。并且,此函数将数字转换为八进制并返回到main()
函数
在此程序中,八进制数首先转换为十进制。然后,将十进制数转换为二进制数。
#include
#include
using namespace std;
long long convertOctalToBinary(int);
int main()
{
int octalNumber;
cout << "Enter an octal number: ";
cin >> octalNumber;
cout << octalNumber << " in octal = " << convertOctalToBinary(octalNumber) << "in binary";
return 0;
}
long long convertOctalToBinary(int octalNumber)
{
int decimalNumber = 0, i = 0;
long long binaryNumber = 0;
while(octalNumber != 0)
{
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
}
return binaryNumber;
}
输出
Enter an octal number: 54
54 in octal = 101100
用户输入的八进制数将传递给convertOctalToBinary()
函数。并且,此函数将数字转换为二进制并返回main()
函数