编写一个to_base_n()函数接受两个在2-10范围内的参数,然后以第1个参数中制定的进制打印第2个参数的数值。例如,to_base_n(129,8)显示的结果为201,也就是129的八进制数。在一个完整的程序中测试该函数。
以下为代码:
#include <stdio.h>
void to_base_n(int n, int x);
int main(void)
{
int n, x;
printf("Enter a number and the base for the form of prints.\n");
printf("Now enter the number in the demical system: ");
scanf("%d", &x);
printf("Enter the base of it(2-10): ");
scanf("%d", &n);
while(n < 2 && n > 10)
{
printf("Enter the base(2-10): ");
scanf("%d", &n);
}
to_base_n(n, x);
return 0;
}
void to_base_n(int n, int x)
{
if(x < 0)
{
x *= -1;
printf("-");
}
if(x > 0)
{
to_base_n(n, x / n);
printf("%d", x % n);
}
return;
}