用栈实现十进制到其他进制的转换,此处最大进制设为十六进制,可以自行拓展。
主要方法:除商倒数取余
#include <iostream>
using namespace std;
//栈节点,使用的是链栈结构
struct node {
int data;
struct node *next ;
};
//进栈,需要返回指针类型,因为传指针到里面只能更改指针所指的值,而不能更改指针本身的值
struct node * push( struct node *top, int n)
{
struct node *s=new node;
s-> data=n;
s-> next=top;
top= s;
return top;
}
//出栈,并将余数放入到n中
struct node * popit( struct node *top, int &n )
{
n= top->data ;
struct node *p=top;
top= top->next ;
delete p;
return top;
}
int main ()
{
struct node *top= NULL;//初始化
int n,base ;
cout<<" 待转换的整数: "<<endl ;
cin>>n ;
cout<<" 转换为多少进制: "<<endl ;
cin>>base ;
while(n) //利用除商取余法将余数压入栈中,直到n为0
{
top=push (top, n%base );
n/=base ;
}
int k=0;
while(top!=NULL )//将余数倒着取出并显示
{
top=popit (top, k);
if (k<10)
{
cout<<k ;
continue;
}
switch(k)
{
case 10:
cout<<"A" ;continue;
case 11:
cout<<"B" ;continue;
case 12:
cout<<"C" ;continue;
case 13:
cout<<"D" ;continue;
case 14:
cout<<"E" ;continue;
case 15:
cout<<"F" ;continue;
default:
cout<<k ;
}
}
system("pause" );
return 0;
}