原文: https://www.programiz.com/cpp-programming/examples/octal-decimal-convert
要理解此示例,您应该了解以下 C++ 编程主题:
#include <iostream>
#include <cmath>
using namespace std;
int octalToDecimal(int octalNumber);
int main()
{
int octalNumber;
cout << "Enter an octal number: ";
cin >> octalNumber;
cout << octalNumber << " in octal = " << octalToDecimal(octalNumber) << " in decimal";
return 0;
}
// Function to convert octal number to decimal
int octalToDecimal(int octalNumber)
{
int decimalNumber = 0, i = 0, rem;
while (octalNumber != 0)
{
rem = octalNumber % 10;
octalNumber /= 10;
decimalNumber += rem * pow(8, i);
++i;
}
return decimalNumber;
}
输出
Enter an octal number: 2341
2341 in octal = 1249 in decimal
在程序中,八进制数存储在变量octalNumber
中,并传递给函数octalToDecimal()
。
该函数将用户传递的八进制数转换为其等效的十进制数,并将其返回给main()
函数。
#include <iostream>
#include <cmath>
using namespace std;
int decimalToOctal(int decimalNumber);
int main()
{
int decimalNumber;
cout << "Enter a decimal number: ";
cin >> decimalNumber;
cout << decimalNumber << " in decimal = " << decimalToOctal(decimalNumber) << " in octal";
return 0;
}
// Function to convert decimal number to octal
int decimalToOctal(int decimalNumber)
{
int rem, i = 1, octalNumber = 0;
while (decimalNumber != 0)
{
rem = decimalNumber % 8;
decimalNumber /= 8;
octalNumber += rem * i;
i *= 10;
}
return octalNumber;
}
输出
Enter an decimal number: 78
78 in decimal = 116 in octal
在程序中,十进制数存储在变量decimalNumber
中,并传递给函数decimalToOctal()
。
该函数将用户传递的十进制数转换为其等效的八进制数,并将其返回给main()
函数。