欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
输入一个十进制数,利用栈操作,将该数转换成n进制数。
#include<stdio.h>
#include<stdlib.h>
#define SIZE 20
#define MORE 10
typedef struct{
int *base;
int top;
int stacksize;
}SqStack;
void InitStack(SqStack &S){
//构造一个空栈
S.base=(int *)malloc(SIZE*sizeof(int));
if(!S.base) return ;
S.top=0;
S.stacksize=SIZE;
}
int StackEmpty(SqStack &S){
//判空 是返回1 否返回0
if(S.top==0) return 1;
else return 0;
}
void Push(SqStack &S,int e){
//入栈
if(S.top>=S.stacksize){
S.base=(int *)realloc(S.base,(S.stacksize+MORE)*sizeof(int));
if(!S.base) exit(0);
S.stacksize+=MORE;
}
S.base[S.top++]=e;
}
void Pop(SqStack &S,int &e){
//出栈
if(S.top==0) exit(0);
else
e=S.base[--S.top];
}
void GetTop(SqStack &S,int &e){
//取栈顶元素
if(S.top==0) exit(0);
else
e=S.base[S.top-1];
}
void Res(SqStack &S,int n,int d){
//将10进制数n转换为d进制
InitStack(S);
while(n){
Push(S,n%d);
n=n/d;
}
}
int main(){
int n,d,e;
SqStack S;
printf("输入要转换的10进制数以及要转换的进制:");
scanf("%d%d",&n,&d);
Res(S,n,d);
while(!StackEmpty(S)){
Pop(S,e);
printf("%d",e);
}
return 0;
}