#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef int SElemType;//分號不能掉
typedef int Status;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}Sqstack;//定義
Status Init(Sqstack &S){
S.base=(SElemType*)malloc(sizeof(SElemType)*MAXSIZE);
if(!S.base) return OVERFLOW;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}//初始化
Status Push(Sqstack &S,const SElemType &e){//const
int i;
if(S.top-S.base==S.stacksize){
return ERROR;
}
*S.top=e;//S.top++=e;//錯誤數據類型不一樣 沒有帶*
S.top++;
return OK;
} //進棧
Status GetTop(Sqstack S,SElemType &e){
if(S.top==S.base) return ERROR;
e=*(S.top-1);
return OK;
} //讀取棧頂元素
Status Pop(Sqstack &S,SElemType &e){
if(S.top==S.base){
printf("棧空,無法出棧\n");
return ERROR;
}
--S.top;//e=*--S.top; 錯誤點多加了* 會一直循環亂碼
e=*S.top;
return OK;
}//出棧
bool StackEmpty(Sqstack S){
if(S.top==S.base) return 1;
else return 0;
}//判空
Status Clear(Sqstack &S){
if(S.base) S.base=S.top;
return OK;
}//清空
void conversion(int N,int base){//N是要轉換的十進制數 base為轉換的進制 (2,8,16)
SElemType e;//出棧的數
Sqstack S;
Init(S);//構造棧S
printf("請輸入要轉換的數據:\n");
scanf("%d",&N);
while(N<0||N>MAXSIZE){
printf("輸入范圍錯誤,請重新輸入:");
scanf("%d",&N);
}
printf("請輸入要轉換成幾進制:\n");
scanf("%d",&base);
while(base<0||base>MAXSIZE){
printf("輸入范圍錯誤,請重新輸入:");
scanf("%d",&base);
}
while(N){//N作為循環條件
Push(S,N%base);//求余 壓棧
N=N/base;//N減小
}
printf("轉換的數據為:\n");
while(!StackEmpty(S)){//不是空就出棧
Pop(S,e);//出棧的數放在e
printf("%x",e);//x是16進制 來一個輸出一個e 不然會被覆蓋
}
}//十進制轉d進制
int main(){
Sqstack S1;
int N,base;
if(Init(S1)==OK) {
printf("初始化成功!\n");
conversion(N,base);
}
else printf("初始化失敗!");
return 0;
}
//有點搞不懂const

