基於棧二進位制轉化為八進位制
阿新 • • 發佈:2019-02-11
基於棧二進位制數轉化為八進位制數的程式碼如下
#include<time.h> #include<math.h> # include <stdio.h> # include <stdlib.h> #define STACK_INIT_SIZE 20 #define STACKINCREMENT 10 typedef char ElemType; typedef struct { ElemType *base;//棧底指標 ElemType *top;//棧頂指標 int stacksize;//棧當前可使用的最大容量 }sqstack; void InitStack(sqstack *s) { s->base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType)); if(!(s->base))exit(0); s->top = s->base; s->stacksize = STACK_INIT_SIZE; } void Push(sqstack *s,ElemType e) { if(s->top - s->base >= s->stacksize) { s->base = (ElemType*)realloc(s->base,(STACKINCREMENT + s->stacksize)*sizeof(ElemType)); if(!(s->base))exit(0); s->top = s->base+ s->stacksize; s->stacksize = s->stacksize + STACKINCREMENT; } *(s->top) = e; (s->top)++; } void Pob(sqstack *s,ElemType *e) { if(s->top==s->base)return ; s->top--; *e = *(s->top); } int StackLen(sqstack s) { return (s.top - s.base); } int main() { sqstack s,p; int sum = 0; InitStack(&s); InitStack(&p);//存放八進位制數的棧 ElemType c; printf("請輸出將要轉換的二進位制數,最後以+結束"); scanf("%c",&c); while(c!='+') { Push(&s,c); scanf("%c",&c); } int len = StackLen(s); printf("棧的當前容量%d\n",len); int num = len/3; int tt = len%3; int count = 0; for(int i = 0; i < len;i++) { if(num>0 ) { Pob(&s,&c); sum = sum + (c-48)*pow(2.0,count); count++; if(count==3) { num--; c = sum + 48; Push(&p,c); sum = 0; count = 0; } } else { Pob(&s,&c); sum = sum + (c-48)*pow(2.0,count); count++; if(count == tt ) { c = sum + 48; Push(&p,c); } } } len = StackLen(p); printf("八進數棧的當前容量%d\n",len); for(int i = 0;i < len;i++) { Pob(&p,&c); printf("%c",c); } printf("\n"); return 0; }