#include <iostream>
#define MAXSIZE 100
using namespace std;
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
}SqStack;
bool InitStack(SqStack &S)
{
S.base=new SElemType[MAXSIZE];
if(!S.base)
{
cout << "存储分配失败!" << endl;
return false;
}
S.top=S.base;
return true;
}
bool Push(SqStack &S,SElemType e)
{
if(S.top-S.base==MAXSIZE)
return false;
*S.top++=e;
return true;
}
bool Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base)
return false;
e=*--S.top;
return true;
}
bool StackEmpty(SqStack S)
{
if(S.top ==S.base)
{
return true;
}
else
{
return false;
}
}
SElemType GetTop(SqStack S)
{
if(S.top!=S.base)
return *(S.top-1);
}
void conversion(int N,int M)
{
SqStack S;
SElemType e;
InitStack(S);
while(N)
{
Push(S,N%M);
N=N/M;
}
while(!StackEmpty(S))
{
Pop(S,e);
cout<<e;
}
}
void conversion16(int N)
{
SqStack S;
SElemType e;
InitStack(S);
while(N)
{
Push(S,N%16);
N=N/16;
}
while(!StackEmpty(S))
{
Pop(S,e);
if(e==10)
cout<<"A";
else if(e==11)
cout<<"B";
else if(e==12)
cout<<"C";
else if(e==13)
cout<<"D";
else if(e==14)
cout<<"E";
else if(e==15)
cout<<"F";
else if(e<10)
cout<<e;
}
}
int main()
{
SqStack S;
InitStack(S);
int N,x;
SElemType e;
cout<<"请输入需转换数制的数字!\n";
cin>>N;
cout<<"-----数制转换-----"<<endl;
cout<<"转换为2进制 [1]"<<endl;
cout<<"转换为8进制 [2]"<<endl;
cout<<"转换为16进制[3]"<<endl;
cout<<"退出[0]"<<endl;
cout<<"请输入你的选择:";
cin>>x;
while(x)
{ switch(x)
{ case 1:conversion(N,2); break;
case 2:conversion(N,8); break;
case 3:conversion16(N); break;
case 0:break;
default:cout<<"你的选择有错,请重新选择!" ;
}
cout<<"\n请输入你的选择:"; cin>>x;
}
return 0;
}
【数据结构作业三】利用栈(以顺序栈作存储结构)实现二、十和十六进制转换
最新推荐文章于 2023-11-26 12:53:14 发布