用栈(链式)实现十进制到其他进制的转换:

用栈实现十进制到其他进制的转换,此处最大进制设为十六进制,可以自行拓展。

主要方法:除商倒数取余

#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;

}


  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值