改进版进制转换

#include<iostream>
using namespace std;
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef int Status;
typedef struct SNode{
    int data;
    struct SNode *next;
}SNode,*LinkStack;

Status InitStack(LinkStack &S){
     S = NULL;
     return OK;
}

Status Push(LinkStack &S,int m){
    SNode *p=new SNode;
    if(!p)
        return OVERFLOW;
    p->data=m;
    p->next=S;
    S=p;
    return OK;
}

Status Pop(LinkStack &S,int &m){
       SNode *p;
       if(!S)
           return ERROR;
      m=S->data;
      p=S;
      S=S->next;
      delete p;
      return OK;
}

bool StackEmpty(LinkStack &S){
     if(!S)
         return true;
     return false;
}
void conversion(int num){//此函数可以任意转换成16进制,8进制,2进制 
     LinkStack S;
     int num_fir,num_sec;
     InitStack(S);
     cout<<"输入你想要转换的进制数:"<<endl; 
     cin>>num_fir;
     if(num_fir!=16){
         while(num){
            Push(S,num%num_fir);
            num/=num_fir;
         }
         cout<<"该数字转换成"<<num_fir<<"进制后为"<<endl;
         while(!StackEmpty(S)){
            Pop(S,num_sec);
            cout<<num_sec;
         }
     }
     else{
          while(num){
             Push(S,num%num_fir);
             num/=num_fir;
          }
          cout<<"该数字转换成16进制后为"<<endl;
          while(!StackEmpty(S)){
              Pop(S,num_sec);
              if(num_sec>9)
                 printf("%c",num_sec+55);
              cout<<num_sec;
          }
     }
     cout<<endl;
}
int main(){
    int n;
    while(true){
       cout<<"请输入你所要转换的十进制数字:"<<endl;
	   cout<<"如果你想要退出,请输入-1:"<<endl;
       cin>>n;
       if(n==-1)
          break;
       conversion(n);
    }
} 

你可能感兴趣的:(改进版进制转换)