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;
}
#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;
}
输出结果为:
输入一个十进制数: 78
十进制数 78 转换为八进制为 116
实例 - 八进制转换为十进制
#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;
}
#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;
}
输出结果为:
输入一个八进制数: 116
八进制数 116 转换为十进制为 78