利用栈先进后出的原理帮助实现将十进制数转换为二至九进制数的功能。
源代码:
#include <iostream>
using namespace std;
const int maxsize=100;
class Sstack
{
public:
Sstack(){top=-1;}
~Sstack(){};
void push(int x);
int getpop(){if(top!=-1)return data[top];};
int pop();
int empty();
void decimaltor(int n,int m);
private:
int data[maxsize];
int top;
};
void Sstack::push(int x)
{
if(top==maxsize)throw"上溢";
else{
data[++top]=x;
}
}
int Sstack::pop()
{
if(top==-1)throw"下溢";
else{
int x;
x=data[top--];
return x;
}
}
int Sstack::empty()
{
if(top==-1){return 1;}
else{return 0;}
}
void Sstack::decimaltor(int n,int m)
{
top=-1;
int t;
while (n!=0)
{
t=n%m;
push(t);
n=n/m;
}
while(top!=-1)
{
cout<<pop();
}
}
int main()
{
int n,m;
cout<<"请输入想要转换的数字:";
cin>>n;
cout<<"转化为x进制,请输入x:";
cin>>m;
Sstack a;
cout<<n<<"的"<<m<<"进制为";
a.decimaltor(n,m);
cout<<endl;
return 0;
}
实验结果: