#include <stdio.h>
int decimal_to_binary(unsigned int number)
{
return number == 0 ? 0 : number % 2 + 10 * decimal_to_binary(number / 2);
}
void test()
{
const int sets[][2] =
{
{0, 0}, {1, 1}, {2, 6}, {3, 11}, {5, 60}, {6, 10}, {7, 100},
};
for (int i = 0, size = sizeof(sets) / sizeof(sets[0]); i < size; ++i)
{
printf("res:%d\n",decimal_to_binary(sets[i][0]));
}
}
int main()
{
test();
return 0;
}
测试结果:
binary[0] = 0
binary[1] = 1
binary[2] = 10
binary[3] = 11
binary[4] = 100
binary[5] = 110
binary[6] = 111
?
#include <stdio.h>
int decimal_to_octal(int decimal)
{
if ((decimal < 8) && (decimal > 0))
{
return decimal;
}
else if (decimal == 0)
{
return 0;
}
else
{
return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8);
}
}
int main()
{
int octalNumber, decimalNumber;
printf("\nEnter your decimal number : ");
scanf("%d", &decimalNumber);
octalNumber = decimal_to_octal(decimalNumber);
printf("\nThe octal of %d is : %d", decimalNumber, octalNumber);
return 0;
}
测试结果:
Enter your decimal number : 100
The octal of 100 is : 144
【欢迎关注编码小哥,学习更多实用的编程方法】