代码区
用栈实现进制转换,为类C语言,可以正常运行,而不仅仅是直接的算法!
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100 //规定最大数量
typedef int SElemType;
typedef struct SqStack
{
SElemType *base; //栈底指针
SElemType *top;
int stacksize;
}SqStack;
enum Status{ERROR,OK}; //此处用的是枚举类型,如果以下的函数体为有返回值或者无返回值的,可以不选择枚举类型
//初始化
Status InitStack(SqStack &S)
{
S.base=new SElemType[MAXSIZE]; //申请空间
if(!S.base) //没有申请成功
return ERROR;
S.top=S.base; //空栈
S.stacksize=MAXSIZE; //可用的最大空间
return OK;
}
//进栈
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base==S.stacksize) //若栈满
return ERROR;
*S.top=e; //第一个进的,落底
S.top++; //指针上移
return OK;
}
//出栈
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base) //栈空
return ERROR;
S.top--;
e=*S.top;
return OK;
}
//判断栈是否为空
Status StackEmpty(SqStack S) //其实这个函数可以用语句代替
{
if(S.top==S.base)
return OK;
else
return ERROR;
}
//十进制转换为二进制
Status Binary(int n)
{
SqStack S;
SElemType e;
InitStack(S);
while(n)
{
Push(S,n%2); //让n的余数依次进栈
n=n/2;
}
while(!StackEmpty(S))
{
Pop(S,e);
printf("%d ",e);
}
return OK;
}
int main()
{
SqStack S;
int x;
printf("enter a Decimal number\n"); //输入一个十进制数
scanf("%d",&x);
InitStack(S);
Binary(x);
return 0;
}