堆棧的應用-進位的轉換

來源:互聯網
上載者:User

學了堆棧,我們都會瞭解,它的一個顯著的特點:先進後出,就像把東西放在桶子裡面,先放的在下面,要拿就要從上面開始拿出來。瞭解這個原理,就好了。

來一個實用的吧,就是進位的轉換。二,八,十,十六進位的相互轉換。(本程式對十六進位,含有字母的沒做處理,但由其他進位的可以轉成十六進位)就是有一點點瑕疵。

不過,這個問題不大,把輸入的字母轉化為數字就行了。其他的都可實現啦。

#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");}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.