进制转换可以用递归来做,其实用递归呢也是用堆栈来实现的
下面的这段程序是用堆栈实现的:并通过测试
#include <stdio.h>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
#define SElemtype int
typedef struct
{
SElemtype *top;
SElemtype *base;
int stacksize;
}SqStack;
typedef enum
{
OK,
ERROR
}Status;
int InitStack(SqStack *s)
{
s->base=(SElemtype *)malloc(STACK_INIT_SIZE*sizeof(SElemtype));
if(!s->base)
return ERROR;
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
return OK;
}
int Push(SqStack *s,SElemtype item)
{
if(s->top-s->base>=s->stacksize)//如果堆栈已满就增加空间
{
s->base=(SElemtype*)realloc(s->base,(s->stacksize+STACK_INCREMENT)*sizeof(SElemtype));
if(!s->base)
{
return ERROR;
}
s->stacksize+=STACK_INCREMENT;
}
*s->top=item;
s->top++;
return OK;
}
int Pop(SqStack *s,SElemtype *item)
{
if(s->base==s->top)//堆栈为空
{
return ERROR;
}
s->top--;
*item=*cs->top;
return OK;
}
int Gettop(SqStack *s,SElemtype *item)
{
if(s->base==s->top)//堆栈为空
{
return ERROR;
}
*item=*(--(s->top));
s->top++;
return OK;
}
int convert(int a)
{
SElemtype tmp;
SqStack s;
InitStack(&s);
while(a)
{
Push(&s,a%16);
a/=16;
}
while(Pop(&s,&tmp)!=ERROR)
{
if(tmp<=9)
printf("%c",tmp+'0');
else
printf("%c",tmp-10+'A');
}
return OK;
}
int main(int argc,char *argv[])
{
int input;
printf("This system will convert decimal system to hex\n please input the decimal number\n");
scanf("%d",&input);
convert(input);
return EXIT_SUCCESS;
}