/*
用顺序栈实现进制的转换
*/
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef int SElemType;
typedef int Status;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//构造一个空栈
Status initStack(SqStack *s)
{
s->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!s->base)
{
exit(OVERFLOW);
}
printf("创建成功!\n");
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
return OK;
}
//入栈
Status push(SqStack *s, SElemType e)
{
//栈满,追加存储空间
if(s->top - s->base >= s->stacksize)
{
s->base = (SElemType *)realloc(s->base,(s->stacksize + STACKINCREMENT) * sizeof(SElemType));
if(!s->base)
{
exit(OVERFLOW);
}
s->top = s->base + s->stacksize;
s->stacksize += STACKINCREMENT;
}
*s->top++ = e;
return OK;
}
//出栈
Status pop(SqStack *s, int &div)
{
if(s->top == s->base)
{
return ERROR;
}
div = * --s->top; //***************
return OK;
}
/*判空*/
Status stackEmpty(SqStack *s)
{
if(s->top == s->base )
return OK;
else
return ERROR;
}
/*进制转换,对于输入的任意一个非负十进制整数,打印输出与其等值的八进制数*/
void conversion(SqStack *s)
{
int num, e, N;
puts("请输入一个非负十进制整数:");
scanf("%d",&num);
puts("请选择转换为的进制:(2/8/16)");
/*判断输入的进制是否正确*/
while(1)
{
scanf("%d",&N);
if(N != 2 && N != 8 && N != 16)
{
printf("输入有误!请重新输入:");
}
else
break;
}
printf("十进制%d转换成%d进制:",num, N);
while(num)
{
push(s, num % N);
num /= N;
}
while(!stackEmpty(s))
{
pop(s, e);
/* if(N == 16 && e >9)
{
e = e + 'A' - 10;
printf("%c",e);
}
else
printf("%c",e);
*/
if(N == 16 && e > 9)
{
switch(e)
{
case 10 : printf("%c",'A');break;
case 11 : printf("%c",'B');break;
case 12 : printf("%c",'C');break;
case 13 : printf("%c",'D');break;
case 14 : printf("%c",'E');break;
case 15 : printf("%c",'F');break;
}
}
else
printf("%d",e);
}
puts(""); //换行
}
void main()
{
SqStack s;
initStack(&s);
conversion(&s);
}
数据结构练习:用顺序栈实现进制间的转换
最新推荐文章于 2023-04-23 18:25:38 发布