利用栈实现十进制对二进制,八进制、十六进制的任意转换(N进制)
1、程序代码如下(利用栈的动态分配实现):
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define INITSIZE 10
#define INCREMENT 2
typedef int Status;
typedef int Elemtype;
typedef struct{
Elemtype *base;
Elemtype *top;
int StackSize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base=(Elemtype*)malloc(sizeof(Elemtype)*INITSIZE);
if(!S->base)
{
return ERROR;
}
S->top=S->base;
S->StackSize=INITSIZE;
return OK;
}
Status PushStack(SqStack *S,Elemtype e)
{
if( S->top - S->base >= S->StackSize)
{
S->base=(Elemtype*)realloc(S->base,(S->StackSize+INCREMENT)*sizeof(Elemtype));
if(!S->base)
{
return ERROR;
}
S->top = S->base+S->StackSize;
S->StackSize+=INCREMENT;
}
*S->top=e;
S->top++;
return OK;
}
Status StackEmpty(SqStack *S)
{
if(S->top == S->base)
{
return OK;
}
return ERROR;
}
Status PopStack(SqStack *S,Elemtype *e)
{
if(S->top == S->base)
{
return ERROR;
}
*e=*--S->top;
return OK;
}
void Fun_10_2_8_16(int number,int cet)
{
SqStack S;
Elemtype e;
InitStack(&S);
if(number==0)
{
printf("转换后的%d进制数为:0",cet);
return ;
}
while(number)
{
PushStack(&S,number%cet);
number=number/cet;
}
printf("转换后的%d进制数为:",cet);
while(!StackEmpty(&S))
{
PopStack(&S,&e);
switch(e) //整型数转成字符输出
{
case 10:
case 11:
case 12:
case 13:
case 14:
case 15: e+=55;break;
default :e+=48;
}
printf("%c",e);
}
}
int main()
{
int number,cet;
printf("请输入要转换的十进制数:");
scanf("%d",&number);
printf("请输入要转换的数制:");
scanf("%d",&cet);
Fun_10_2_8_16(number,cet);
return 0;
}
2、运行截图:
还没有评论,来说两句吧...