C语言程序:输入一个2/8/10/16进制数,将其转换到2/8/10/16进制数
- 提问者网友:做自己de王妃
- 2021-07-18 11:16
- 五星知识达人网友:动情书生
- 2021-07-18 12:30
#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);
int main(void)
{
int source;
int object;
int length;
long decimal_num;
char temp[MAXCHAR];
int flag=1;
printf("你好\n");
while(flag)
{
printf("zhuan huan qian de shu shi:\n");
scanf("%s",temp);
printf("zhuan huan qian de shu zhi:\n");
scanf("%d",&source);
printf("zhuan huan hou de shu zhi:\n");
scanf("%d",&object);
printf("zhuan huan hou de shu shi:\n");
decimal_num=source_to_decimal(temp,source);
length=decimal_to_object(temp,decimal_num,object);
output(temp,length);
printf("ji xu,shu ru 1,bu ji xu shu ru 0:\n");
scanf("%d",&flag);
}
printf("bye!\n");
return 0;
}
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");