在此示例中,您將學(xué)習(xí)通過(guò)創(chuàng)建用戶定義的函數(shù)將八進(jìn)制數(shù)與十進(jìn)制數(shù)相互轉(zhuǎn)換。
要理解此示例,您應(yīng)該了解以下C語(yǔ)言編程主題:
#include <stdio.h> #include <math.h> int convertDecimalToOctal(int decimalNumber); int main() { int decimalNumber; printf("輸入十進(jìn)制數(shù)字: "); scanf("%d", &decimalNumber); printf("%d(十進(jìn)制)= %d(八進(jìn)制)", 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; }
輸出結(jié)果
輸入十進(jìn)制數(shù)字: 116 116(十進(jìn)制)= 164(八進(jìn)制)
#include <stdio.h> #include <math.h> long long convertOctalToDecimal(int octalNumber); int main() { int octalNumber; printf("輸入八進(jìn)制數(shù)字: "); scanf("%d", &octalNumber); printf("%d(八進(jìn)制) =%lld(十進(jìn)制)", 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; }
輸出結(jié)果
輸入八進(jìn)制數(shù)字: 164 164(八進(jìn)制) =116(十進(jìn)制)