首页
/
每日頭條
/
生活
/
八進制轉換二進制方法
八進制轉換二進制方法
更新时间:2024-11-14 15:59:32

題目要求:

編寫一個程序,要求從終端輸入一串0/1表示的二進制數,輸出它的八進制表示形式。

八進制轉換二進制方法(二進制八進制轉換器)1

二進制轉八進制的過程

将棧A的10轉換為2,存放到棧B中;

主要考點是練習動态申請内存空間;

#include "stdio.h" #include "math.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*/ s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType)); if(!s->base) exit(0); /*分配空間失敗*/ s->top = s->base; /*最開始,棧頂就是棧底*/ s->stacksize = STACK_INIT_SIZE; /*最大容量為STACK_INIT_SIZE */ } /*入棧操作,将e壓入棧中*/ void Push(sqStack *s, ElemType e){ if(s->top - s->base >= s->stacksize){ /*棧滿,追加空間*/ s->base = (ElemType *)realloc(s->base, (s->stacksize STACKINCREMENT)*sizeof(ElemType)); if(!s->base) exit(0); /*存儲分配失敗*/ s->top = s->base s->stacksize; s->stacksize = s->stacksize STACKINCREMENT; /*設置棧的最大容量*/ } *(s->top) = e; /*放入數據*/ s->top ; } /*出棧操作,用e将棧頂元素返回*/ void Pop(sqStack *s , ElemType *e){ if(s->top == s->base) return; *e = *--(s->top); } /*計算棧s的當前長度*/ int StackLen(sqStack s){ return (s.top - s.base) ; } main() { ElemType c; sqStack s1; sqStack s2; int len,i,j,sum = 0; initStack(&s1); /*創建一個棧s1,用來存放二進制字符串*/ printf("Please input a binary number and type # for end\n"); /*輸入0/1字符表示的二進制數,以#結束*/ scanf("%c",&c); while(c!='#') { if(c=='0' || c=='1') Push(&s1,c); scanf("%c",&c); } initStack(&s2); /*創建一個棧s2,用來存放八進制字符串*/ len = StackLen(s1); /*得到棧中的元素個數,即二進制數的長度*/ for(i=0;i<len;i=i 3){ for(j=0;j<3;j ){ Pop(&s1,&c); /*取出棧頂元素*/ sum = sum (c-48) * pow(2,j); /*轉換為八進制數*/ if(s1.base == s1.top) break; } Push(&s2,sum 48) ; /*将八進制數以字符形式壓入棧中*/ sum = 0; } while(s2.base != s2.top ){ /*輸出八進制棧的内容*/ Pop(&s2,&c); printf("%c",c); } getche(); }

運行結果:

八進制轉換二進制方法(二進制八進制轉換器)2

運行結果

,
Comments
Welcome to tft每日頭條 comments! Please keep conversations courteous and on-topic. To fosterproductive and respectful conversations, you may see comments from our Community Managers.
Sign up to post
Sort by
Show More Comments
Copyright 2023-2024 - www.tftnews.com All Rights Reserved