编写一个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;
}
本文介绍如何编写一个名为to_base_n的函数,接收2到10范围内的基数和整数,将整数转换为目标基数的表示形式。通过实例演示和输入验证,展示了函数的使用方法。
470

被折叠的 条评论
为什么被折叠?



