#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INSEASIBLE -1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType*base;
ElemType*top;
int stacksize;
}SqStack;
//构造一个空栈S
Status InitStack_Sq(SqStack &S){
S.base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
//获得顺序栈中的栈顶元素,用e返回
Status GetTop(SqStack S,ElemType &e){
if(S.base==S.top) return ERROR;
e=*(S.top-1);
return OK;
}
//入栈插入新元素e
Status Push(SqStack &S,ElemType e){//判断当前存储空间是否已满,如果已满,增加分配
if(S.top-S.base>=S.stacksize){
S.base =(ElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(ElemType));
if(!S.base ) exit(OVERFLOW);
S.top=S.base;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}
//出栈,用e返回栈顶元素
Status Pop(SqStack &S,ElemType &e){
if(S.base==S.top) return ERROR;
e=*--S.top;
return OK;
}
//顺序栈显示函数,从栈底到栈顶每个元素逐个显示出来
void StackDisp_Sq(SqStack S){
ElemType *p;
printf("\n当前栈中的数据是: \n");
p=S.base;
while(p<S.top){
printf("%d\t",*p); p++;
}
printf("\n数据显示完毕! \n\n");
}
//进制转换
void change(SqStack &S,int m,int n){
while(m){
Push(S,m%n);
m/=n;
}
}
//判断栈空
Status StackEmpty(SqStack S){
if(S.base==S.top) return true;
else return false;
}
int main(){
SqStack S;
printf("请输入需要转换数的个数");
int cir;
scanf("%d",&cir);
for(int cle=0;cle<cir;cle++)
{
InitStack_Sq(S);
int number;
printf("\n-------------------------------------------------\n");
printf("请选择要执行的任务序号(1或者2):\n");
printf("1.十进制数转其他进制\n");
printf("2.其他进制数转十进制\n");
scanf("%d",&number);
if(number==1){
printf("请输入要转换的十进制数:\n");
int m;
scanf("%d",&m);
printf("请输入要转换为几进制:\n");
int n;
scanf("%d",&n);
change(S,m,n);
printf("十进制的%d转换为%d进制的结果为:\n",m,n);
int e;
while(Pop(S,e)){
printf("%d",e);
}
}else if(number==2){
printf("请输入原数为几进制:\n");
int m;
scanf("%d",&m);
printf("请输入原数的值:\n");
int n;
scanf("%d",&n);
int c=n;
int i=0,sum=0;
while(c){
sum+=c%10*pow(m,i);
i++;
c/=10;
}
printf("%d进制的%d转换为十进制为%d\n",m,n,sum);
}else{
printf("输入错误!请重载程序!");
}
}
printf("\n-------------------------------------------------\n");
printf("\nOVER!");
}
大佬们不喜勿喷,感谢观看!