我们在学习c语言时,进制转换是比较基础的,我们一般是取余,取余。
重复着同一动作,不断递减,这里我们可以考虑用递归的方法来尝试一下。
递归的出口是,商为0,递归过程就是不断取余。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void convto(char *s, int n, int b)
{
char bit[]={"0123456789ABCDEF"};
int len;
if(n==0){
strcpy(s,"");
return ;
}
convto(s,n/b,b);
len=strlen(s);
s[len]=bit[n%b];
s[len+1]='\0';
}
int main(int argc, char *argv[]) {
char s[80];
int i,base,old;
printf("Enter the decimal you want to convert:\n");
scanf("%d",&old);
printf("Enter the base to be converted:\n");
scanf("%d",&base);
convto(s,old,base);
printf("%s\n",s);
return 0;
}
可以来看一下结果
Enter the decimal you want to convert:
123
Enter the base to be converted:
2
1111011
--------------------------------
Process exited after 4.768 seconds with return value 0
请按任意键继续. . .
其实试了一下八进制,程序也是可行的。
Enter the decimal you want to convert:
123
Enter the base to be converted:
8
173
--------------------------------
Process exited after 4.468 seconds with return value 0
请按任意键继续. . .
另外,如果有小伙伴想要将转换的数变成数时,可以用atof转换,不过只能转成int型,同时记得要添加stdlib.h头文件。