💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# C 程序:将八进制数转换为十进制,反之亦然 > 原文: [https://www.programiz.com/c-programming/examples/octal-decimal-convert](https://www.programiz.com/c-programming/examples/octal-decimal-convert) #### 在此示例中,您将学习通过创建用户定义的函数将八进制数手动转换为十进制,反之亦然。 要理解此示例,您应该了解以下 [C 编程](/c-programming "C tutorial")主题: * [C 函数](/c-programming/c-functions) * [C 用户定义的函数](/c-programming/c-user-defined-functions) * * * ## 示例 1:将十进制转换为八进制的程序 ```c #include <stdio.h> #include <math.h> int convertDecimalToOctal(int decimalNumber); int main() { int decimalNumber; printf("Enter a decimal number: "); scanf("%d", &decimalNumber); printf("%d in decimal = %d in octal", decimalNumber, convertDecimalToOctal(decimalNumber)); return 0; } int convertDecimalToOctal(int decimalNumber) { int octalNumber = 0, i = 1; while (decimalNumber != 0) { octalNumber += (decimalNumber % 8) * i; decimalNumber /= 8; i *= 10; } return octalNumber; } ``` **输出** ```c Enter a decimal number: 78 78 in decimal = 116 in octal ``` ## 示例 2:将八进制转换为十进制的程序 ```c #include <stdio.h> #include <math.h> long long convertOctalToDecimal(int octalNumber); int main() { int octalNumber; printf("Enter an octal number: "); scanf("%d", &octalNumber); printf("%d in octal = %lld in decimal", octalNumber, convertOctalToDecimal(octalNumber)); return 0; } long long convertOctalToDecimal(int octalNumber) { int decimalNumber = 0, i = 0; while(octalNumber != 0) { decimalNumber += (octalNumber%10) * pow(8,i); ++i; octalNumber/=10; } i = 1; return decimalNumber; } ``` **输出** ```c Enter an octal number: 116 116 in octal = 78 in decimal ```