自然语言解决问题:该题目主要用来处理不同进制间互相转化,将原数转换成十进制数字,接着求出转换成目标数制后字符数组的长度,并逆序打印字符数组。
具体代码:
#include <stdio.h>
#define MAXCHAR 101
int char_to_num(char ch);
char num_to_char(int num);
long source_to_decimal(char temp[],int source);
int decimal_to_object(char temp[],long decimal_num,int object);
void output(char temp[],int length);
main()
{
int source;
int object;
int length;
long decimal_num;
char temp[MAXCHAR];
int flag=1;
while(flag)
{
printf("转换前的数是:");
scanf("%s",temp);
printf("转换前的数制是:");
scanf("%d",&source);
printf("转换后的数制是:");
scanf("%d",&object);
printf("转换后的数是:");
decimal_num=source_to_decimal(temp,source);
length=decimal_to_object(temp,decimal_num,object);
output(temp,length);
printf("继续请输入1,否则输入0: \n");
scanf("%d",&flag);
}
}
int char_to_num(char ch){
if(ch>='0'&&ch<='9')
return ch-'0';
else
return ch-'A'+10;
}
char num_to_char(int num)
{
if(num>=0&&num<=9)
return (char)('0'+num-0);
else
return (char)('A'+num-10);
}
long source_to_decimal(char temp[],int source)
{
long decimal_num=0;
int length;
int i;
for(i=0;temp[i]!='0';i++);
length=i;
for(i=0;i<=length-1;i++)
decimal_num=(decimal_num*source)+char_to_num(temp[i]);
return decimal_num;
}
int decimal_to_object(char temp[],long decimal_num,int object)
{
int i=0;
while(decimal_num)
{
temp[i]=num_to_char(decimal_num%object);
decimal_num=decimal_num/object;
i++;
}
temp[i]='\0';
return i;
}
void output(char temp[],int length)
{
int i;
for(i=length-1;i>=0;i--)
printf("%c",temp[i]);
printf("\n");
}