请编程实现利用栈(stack)来作数制转换应用。
说明: 输入十进制数字N转换成r进制数字(分別2、8、16进制),将其结果显示出来。方法是利用N除以r,所得的余数入栈,直到商为0止。再将栈所存放数字,依逆序出栈即可。
例:5410=1101102=668=3616
25410=111111102=3768=FE16
#include <iostream>
#include <cstdlib>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct SNode{
int data;
struct SNode *next;
} SNode, *LinkStack;
Status InitStack(LinkStack &S){
S=NULL;
return OK;
}
bool StackEmpty(LinkStack S){
if(!S) return true;
return false;
}
Status Push(LinkStack &S, int e){
LinkStack p;
p=new SNode;
if(!p)return OVERFLOW;
p->data=e;
p->next=S;
S=p;
return OK;
}
Status Pop(LinkStack &S,int &e){
LinkStack p;
if(!S)return ERROR;
e=S->data;
p=S;
S=S->next;
delete p;
return OK;
}
void conversion(int N,int r){
int e;
if(N==0)cout<<0;
else{
LinkStack S;
InitStack(S);
while(N){
Push(S,N % r);
N=N/r;
}
while(!StackEmpty(S)){
Pop(S,e);
if(r==16&&e>9)
switch(e){
case 10:cout<<'A';break;
case 11:cout<<'B';break;
case 12:cout<<'C';break;
case 13:cout<<'D';break;
case 14:cout<<'E';break;
case 15:cout<<'F';break;
}
else
cout<<e;
}
}
}
int main(){
int n=-1,r=2;
while (n<0){
cout<<"Please input the converting number n(n>=0):"<<endl;
cin>>n;
}
cout<<"\nThe converted result:\n";
cout<<"\nThe binary number: ";
conversion(n,r);
cout<<endl;
r=8 ;
cout<<"\nThe Octal number: ";
conversion(n,r);
cout<<endl;
r=16;
cout<<"\nThe hexadecimal number: ";
conversion(n,r);
cout<<endl<<endl;
system("pause");
return 0;
}