编写一个 to_base_n() 函数,接受两个参数,且第二个参数在 2 ~ 10 范围内,然后以第二个参数中指定的进制打印第一个参数的数值。例如,to_base_n(129, 8) 显示结果 201,也就是 129 的八进制数。在一个完整的程序中测试该函数。
#include <stdio.h>
void to_base_n(unsigned long n, unsigned short t);
/* 进制转换,待转换数类型是正整数,因此使用无符号类型标识。*/
int main(void) {
unsigned long number;
unsigned short target;
printf("Enter the integer and N for notation(q to quit):");
while(scanf("%lu %hu",&number, &target) == 2){
if(target < 2 || target > 16){
printf("Please input N between 2 ~ 16!\n");
printf("Enter the integer and N for notation(q to quit):");
continue;
}
printf("Convert %lu to %hu notation is: ",number,target);
to_base_n(number, target);
putchar('\n');
printf("Enter the integer and N for notation(q to quit):");
}
return 0;
}
void to_base_n(unsigned long n, unsigned short t)
{
if(t <2 || t >16){
printf("The function noly convert 2 ~ 16\n");
return;
}
int r;
r = n % t;
if(n >= 2) to_base_n(n/t, t);
if(r<=9) printf("%d",r);
else if(r==10) putchar('A');
else if(r==11) putchar('B');
else if(r==12) putchar('C');
else if(r==13) putchar('D');
else if(r==14) putchar('E');
else if(r==15) putchar('F');
}