栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

利用栈进行进制转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用栈进行进制转换


方法一 (硬算)

#include 
#include 
#include 
#include 
typedef struct StackNode{
int data;
struct StackNode *next;
}StackNode,*linkstack;
void InitStack(linkstack *S){
*S=NULL;
}
void PushStack(linkstack *S,int x){
StackNode *p;
p=NULL;
p=(linkstack)malloc(sizeof(StackNode));
(*p).data=x;
(*p).next=*S;
*S=p;
}
void PopStack(linkstack *S,int *x){
StackNode *p;
if(*S==NULL)
    printf("栈空");
*x=(*S)->data;
p=*S;
*S=(*S)->next;
free(p);
}
bool EmptyStack(linkstack S){
if(S==NULL)
    return true;
else
    return false;
}
int main()
{
   StackNode *S;
   int n,m;
   int i,j,x;
   int sum,num;
   InitStack(&S);
   scanf("%d%d",&n,&m);
   i=0;sum=n;num=0;
   while(pow(m,i)<=n){
    PushStack(&S,i);
    i++;
   }
   printf("%d(10)=",n);
    while(!EmptyStack(S)){
    PopStack(&S,&x);
    num=pow(m,x);
    sum=sum-num;
    if(sum>=0){
      j=1;
      sum=sum+num;
      while(sum-j*pow(m,x)>=0){
        j++;
      }
      printf("%d",j-1);
      sum=sum-(j-1)*pow(m,x);
    }
    else{
     sum=sum+num;
     printf("0");
    }
    }
     printf("(%d)",m);
    return 0;
}

方法二 :

#include 
#include 
#include 
#include 
typedef struct StackNode{
int data;
struct StackNode *next;
}StackNode,*linkstack;
void InitStack(linkstack *S){
*S=NULL;
}
void PushStack(linkstack *S,int x){
StackNode *p;
p=NULL;
p=(linkstack)malloc(sizeof(StackNode));
(*p).data=x;
(*p).next=*S;
*S=p;
}
void PopStack(linkstack *S,int *x){
StackNode *p;
if(*S==NULL)
    printf("栈空");
*x=(*S)->data;
p=*S;
*S=(*S)->next;
free(p);
}
bool EmptyStack(linkstack S){
if(S==NULL)
    return true;
else
    return false;
}
int main()
{
   StackNode *S;
   int n,m;
   int i,j,x;
   InitStack(&S);
   scanf("%d%d",&n,&m);
     printf("%d(10)=",n);
   while(n){
    PushStack(&S,n%m);
    n=n/m;
   }
    while(!EmptyStack(S)){
    PopStack(&S,&x);
    printf("%d",x);
    }
     printf("(%d)",m);
    return 0;
}

节省太多了,呜呜呜

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/665274.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号