今天写一个简易的进制转换程序,能够转换2到10中的任意一个进制。原理就是十进制转换成二进制的取余除法。
程序如下:
#include<stdio.h>
void to_base_n(int n, int b);
int main()
{
int num, base;
printf("enter num and base :");
while (scanf("%d %d", &num, &base) == 2)
{
to_base_n(num, base);
printf("enter annother num and base:");
}
printf("bye!\n");
return 0;
}
void to_base_n(int n, int b)
{
char i;
if (n >= 0&&b>=2&&b<=10)
{
i = n%b;
i = '0' + i;
if (n >= b)
to_base_n(n / b,b);
printf("%c", i);
}
else
printf("error!\n");
}
结果如下:
enter num and base :23 2
10111 enter annother num and base:123 8
173 enter annother num and base:q
bye!
请按任意键继续. . .