ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# C++ 程序:将八进制数转换为十进制,反之亦然 > 原文: [https://www.programiz.com/cpp-programming/examples/octal-decimal-convert](https://www.programiz.com/cpp-programming/examples/octal-decimal-convert) #### 在此示例中,您将学习通过创建用户定义的函数来手动将八进制数转换为十进制,并将十进制数转换为八进制。 要理解此示例,您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题: * [C++ 函数](/cpp-programming/function) * [C++ 中用户定义函数的类型](/cpp-programming/user-defined-function-types) * [C++ `if`,`if...else`和嵌套`if...else`](/cpp-programming/if-else) * [C++ `while`和`do...while`循环](/cpp-programming/do-while-loop) * * * ## 示例 1:将八进制数转换为十进制 ```cpp #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; } ``` **输出** ```cpp Enter an octal number: 2341 2341 in octal = 1249 in decimal ``` 在程序中,八进制数存储在变量`octalNumber`中,并传递给函数`octalToDecimal()`。 该函数将用户传递的八进制数转换为其等效的十进制数,并将其返回给`main()`函数。 ## 示例 2:将十进制数转换为八进制 ```cpp #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; } ``` **输出** ```cpp Enter an decimal number: 78 78 in decimal = 116 in octal ``` 在程序中,十进制数存储在变量`decimalNumber`中,并传递给函数`decimalToOctal()`。 该函数将用户传递的十进制数转换为其等效的八进制数,并将其返回给`main()`函数。