學了堆棧,我們都會瞭解,它的一個顯著的特點:先進後出,就像把東西放在桶子裡面,先放的在下面,要拿就要從上面開始拿出來。瞭解這個原理,就好了。
來一個實用的吧,就是進位的轉換。二,八,十,十六進位的相互轉換。(本程式對十六進位,含有字母的沒做處理,但由其他進位的可以轉成十六進位)就是有一點點瑕疵。
不過,這個問題不大,把輸入的字母轉化為數字就行了。其他的都可實現啦。
#include<stdio.h>#include<math.h>struct stack{ //定義堆棧int num[1000];int top;}stk;void push(struct stack &stk,int p) //入棧函數,引用{ if(stk.top>1000) return;stk.num[stk.top++]=p;}int pop(struct stack &stk){return (stk.num[stk.top--]);}int digit(int a){int i=0;while(a){a/=10;i++;}return i;}void resolve(int c,int a,int d){ int i,t,p,b,k=0; i=digit(a);while(a){int s=a%10;a/=10; push(stk,s); }stk.top--;while(i&&stk.top!=-1){p=pop(stk);b=pow(c,i-1); k+=p*b;i--;}stk.top=0;while(k){t=k%d;k/=d; push(stk,t); } }void putout(struct stack &stk){int q;stk.top--; while(stk.top!=-1){q=pop(stk);switch(q){ case 10:printf("A");break;case 11:printf("B");break;case 12:printf("C");break;case 13:printf("D");break;case 14:printf("E");break;case 15:printf("F");break;case 16:printf("H");break;default :printf("%d",q);break;}}}void main(){int c, n,d;while(1){printf("請輸入該數的進位,及該數,以及要轉換的進位:");scanf("%d%d%d",&c,&n,&d);stk.top=0;resolve(c,n,d);printf("轉化為%d進位後為:",d);putout(stk);printf("\n");}}