用栈的特点完成进制的转换
#include <myhead.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
typedef struct{
int top;
int data[MAX];
}stack,*pstack;
pstack create(){
pstack Z = malloc(sizeof(stack));
if(Z==NULL){
printf("创建失败");
return NULL;
}
Z->top = -1;
return Z;
}
int push(pstack p,int e){
if(p->top==MAX-1){
printf("栈已满");
return -1;
}
p->top++;
p->data[p->top] = e;
return 0;
}
int pop(pstack p){
if(p->top==-1){
printf("栈空,无法出栈");
return -1;
}
int s = p->data[p->top];
p->top--;
return s;
}
void conversion(int a,int b){
int x;
pstack p = create();
if(p==NULL){
return ;
}
while(a>0){
x = a%b;
push(p,x);
a /= b;
}
printf("转换成%d进制为:",b);
while(p->top!=-1){
x = pop(p);
if(x>=10){
printf("%c",x-10+'A');
}else{
printf("%d",x);
}
}
free(p);
printf("\n");
}
int main(int argc, const char *argv[])
{
int a;
int b;
printf("请输入要转换的十进制数:");
scanf("%d",&a);
printf("请输入要转换的进制:");
scanf("%d",&b);
conversion(a,b);
return 0;
}