目录
使用栈的特点完成进制转换
起先实现了转换1-9进制的代码,后来发现再往上走还需涉及到字符的添加,故将栈的datatype改成了 char 型。
通过对输入的数据的取余,利用switch和在遍历函数中的判断从而堪堪实现了过程,以下是代码。
#include<stdio.h>
#include"seqstack.h"
#include<stdlib.h>
//创建
seqStack *create()
{
seqStack *S=(seqStack *)malloc(sizeof(seqStack));
if(NULL==S)
{
printf("创建失败\n");
return NULL;
}
S->top=-1;
printf("创建成功\n");
return S;
}
//判空
int empty(seqStack *S)
{
return S->top==-1? 1:0;
}
//判满
int full(seqStack *S)
{
return S->top==MAX-1 ? 1:0;
}
//入栈,压栈,进栈
int push(seqStack *S,datatype e)
{
//判断逻辑
if(NULL ==S || full(S))
{
printf("入栈失败\n");
return -1;
}
//入栈操作
S->top++;
S->data[S->top]=e;
printf("入栈成功\n");
return 0;
}
//出栈,弹栈
int pop(seqStack *S)
{
if(NULL==S || empty(S))
{
printf("出栈失败\n");
return -1;
}
printf("%c出栈成功\n",S->data[S->top]);
S->top--;
return 0;
}
//遍历栈
void show(seqStack *S)
{
if(NULL ==S ||empty(S))
{
printf("遍历失败\n");
return;
}
printf("从栈顶到栈底:");
for(int i=S->top;i>=0;i--)
{
if(S->data[i]>=65)
{
printf("%c\t",S->data[i]);
}else
{
printf("%d\t",S->data[i]);
}
}
printf("\n");
}
//销毁栈
void destroy(seqStack *S)
{
if(NULL!=S)
{
free(S);
S=NULL;
}
printf("释放成功\n");
}
//10进制转任意进制
int conversion(seqStack *S,int j,int n)
{
int yu;
while(n>=j)
{
yu=n%j;
char y;
switch(yu)
{
case 10: y = 'A';break;
case 11: y = 'B';break;
case 12: y = 'C';break;
case 13: y = 'D';break;
case 14: y = 'E';break;
case 15: y = 'F';break;
default: y = yu;
}
push(S,y);
n=n/j;
}
if(n!=0)
{
switch(n)
{
case 10: n = 'A';break;
case 11: n = 'B';break;
case 12: n = 'C';break;
case 13: n = 'D';break;
case 14: n = 'E';break;
case 15: n = 'F';break;
default: n = n;
}
push(S,n);
}
}
运行结果:
输入了 170 16进制
输出:AA