#include<stdio.h>
#include<string.h>
static char *QUINARY = "01234";
static char *OCTONARY = "01234567";
static char *FIFTNARY = "0123456789ABCDE";
static char buff[10];
char *toQuinary(int num);
char *toOctonary(int num);
char *toFifnary(int num);
char *reverse(char *str);
int main(void)
{
int flag = 1;
int num = 0;
int choice = 0;
while(flag)
{
printf("请输入一个三位数:");
scanf("%d",&num);
printf("转换为几进制? 1--五进制 2--八进制 3--十五进制 0--退出\t");
scanf("%d",&choice);
char *result = "";
switch(choice)
{
case 1:
result = toQuinary(num);
printf("%s\n",result);
break;
case 2:
result = toOctonary(num);
printf("%s\n",result);
break;
case 3:
result = toFifnary(num);
printf("%s\n",result);
break;
default:
flag = 0;
break;
}
}
return 0;
}
char *toQuinary(int num)
{
if(num <= 0) return "0";
int i = 0;
while(num > 0)
{
int ret = num % 5;
buff[i] = QUINARY[ret];
num /= 5;
i++;
}
buff[i]='\0';
return reverse(buff);
}
char *toOctonary(int num)
{
if(num <= 0) return "0";
int i = 0;
while(num > 0)
{
int ret = num % 8;
buff[i] = OCTONARY[ret];
num /= 8;
i++;
}
buff[i]='\0';
return reverse(buff);
}
char *toFifnary(int num)
{
if(num <= 0) return "0";
int i = 0;
while(num > 0)
{
int ret = num % 15;
buff[i] = FIFTNARY[ret];
num /= 15;
i++;
}
buff[i]='\0';
return reverse(buff);
}
char *reverse(char *str)
{
int length = strlen(str);
char copy[length+1];
int i = 0;
for(i=0; i<length;i++)
{
copy[i] = str[length-i-1];
}
copy[i] = '\0';
strcpy(str,copy);
return str;
}
温馨提示:答案为网友推荐,仅供参考