编辑这个页面须要登录或更高权限!
在此示例中,您将学习通过创建用户定义的函数将八进制数与十进制数相互转换。
要理解此示例,您应该了解以下C语言编程主题:
#include <stdio.h> #include <math.h> int convertDecimalToOctal(int decimalNumber); int main() { int decimalNumber; printf("输入十进制数字: "); scanf("%d", &decimalNumber); printf("%d(十进制)= %d(八进制)", 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; }
输出结果
输入十进制数字: 116 116(十进制)= 164(八进制)
#include <stdio.h> #include <math.h> long long convertOctalToDecimal(int octalNumber); int main() { int octalNumber; printf("输入八进制数字: "); scanf("%d", &octalNumber); printf("%d(八进制) =%lld(十进制)", 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; }
输出结果
输入八进制数字: 164 164(八进制) =116(十进制)