栈的应用,学会数制转换

、实验设计方案:1、采用栈的顺序存储结构来实现; 2、用stack类来存储数据,实现栈逻辑上的特点”先进后出”; 3、程序中加入对违规操作的预防语句。【运行结果】程序运行结果如图4所示。图4 程序运行结果 - 进制转换

  1. #include
    using namespace std;

const int Size = 50;
class SeqStack
{
private:
int data[Size]; //数据存储数组
int top;
public:
SeqStack (){top=-1;}
~SeqStack (){}
void Push(int x); //入栈操作
void Pop(); //出栈操作
};

void SeqStack ::Push(int x)
{
top=-1;
int y;
int m=2;
if(top==Size-1) throw "上溢";
while(x!=0)
{
y=x%m;
data[++top]=y;
x=x/m;
};
}

void SeqStack ::Pop()
{
if (top == -1) throw "下溢";
while(top!=-1)
{
int x=data[top--];
cout<<x;
}
}

void main()
{
int i=1;
int number;
SeqStack a;
do{
cout<<"请输入一个十进制整数!"<<endl;
cin>>number;
a.Push(number);
a.Pop();
cout<<endl;
cout<<"若需要继续转换,请输入1;否则请输入0!"<<endl;
cin>>i;
}while(i==1);
}