利用棧實現進位制的轉換!
阿新 • • 發佈:2019-01-01
問題:將十進位制數轉換為任意進位制數(2,8,16...).
演算法:假如N為輸入的數,n為要轉換為的進位制,若要將十進位制231轉換為8進位制數,過程如下;
N N/n N%n
231 28 7
28 3 4
3 0 3
則輸出為347,可以看出,首先得到的應該是7,然後才是4,最後是3,但是要逆序顯示,自然就類似壓棧出棧的資料結構了(陣列也可以實現,但是沒有體現其本質).
所以,只需要初始化棧後,將N%n不斷的壓入棧底,需要注意的是如果要轉換為16進位制,則需要對大於9的數字作字元處理。
/*棧的基本操作*/ #include <stdio.h> #include <malloc.h> //malloc,realloc #include <math.h> //含有overflow #include <process.h> #define S_SIZE 100 //棧的空間大小 #define STACKINCREAMENT 10//增加空間 struct SqStack{ int *base; //棧底 int *top; //棧頂 int stacksize; //棧當前的儲存空間 }; //主函式開始 void main() {//子函式宣告 void InitStack(SqStack &S);//初始化空棧 int StackEmpty(SqStack S);//判空 void GetTop(SqStack S,int &e);//獲得棧頂元素 void push(SqStack &S,int e);//進棧 void pop(SqStack &S,int &e);//出棧 void convert(SqStack &S,int N,int n);//十進位制轉N進位制 int i,num; unsigned n,N;//要轉換成的進位制數和要轉換的數 SqStack s; InitStack(s);//初始化空棧 printf("輸入要轉換的十進位制數和要轉換為的進位制數:\n"); scanf("%d,%d",&N,&n); printf("%d轉換為%d進位制後為:\n",N,n); convert(s,N,n); } void InitStack(SqStack &S) {S.base=(int *)malloc(S_SIZE*sizeof(int)); S.stacksize=S_SIZE; S.top=S.base;//初始化空棧 } int StackEmpty(SqStack S) { if(S.base==S.top) return 1; else return 0; } void GetTop(SqStack S,int &e) {//獲得棧頂元素 e=*(S.top-1); } void push(SqStack &S,int e) {//進棧 if(S.top-S.base>=S.stacksize) {S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREAMENT)*sizeof(int)); S.top=S.base+S.stacksize; S.stacksize+=STACKINCREAMENT;} *(S.top)=e; S.top++; } void pop(SqStack &S,int &e) {//出棧 if(S.base!=S.top) {S.top--; e=*S.top;} } void convert(SqStack &S,int N,int n) { InitStack(S); do {push(S,N%n); N/=n; } while (N!=0); int i,e; while(!StackEmpty(S)) { pop(S,e); if(e>9)//十六進位制時輸出字母 {e=e+55; printf("%c",e);} else printf("%d",e); } printf("\n"); }