Lover雪儿
想念时,就看看天空,无论距离有多远,我们总在同一片天空下!

C语言栈队列实现二-十/二-八进制转换

2015-04-05 Lover雪儿

 

 1 //利用栈来求取二进制数的十进制与八进制的结果
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <math.h>
 5 
 6 #define STACK_INIT_SIZE        20    //初始栈大小
 7 #define STACK_INCREMENT        10  //扩充栈时每次增加的内存
 8 
 9 typedef char ElemType;            //栈中的数据类型
10 typedef struct {
11     ElemType *base;
12     ElemType *top;
13     int stackSize;
14 }sqStack;
15 
16 //初始化栈
17 void init_stack(sqStack *s){
18     s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
19     if(!s->base)
20         exit(-1);
21     s->top = s->base;
22     s->stackSize = STACK_INIT_SIZE;
23 }
24 //入栈
25 void push(sqStack *s,ElemType e){
26     if(s->top - s->base >= s->stackSize){    //检测栈是否已满
27         //若是已满,则自动扩大栈空间
28         s->base = (ElemType *)realloc(s->base, (s->stackSize + STACK_INCREMENT)*sizeof(ElemType));
29         if(!s->base)
30             exit(-1);
31     }
32     *(s->top) = e;
33     s->top++;
34 }
35 //出栈
36 void pop(sqStack *s, ElemType *e){
37     if(s->top == s->base){
38         return ;
39     }
40     *e = *(--(s->top));
41 }
42 //求栈数据的个数,由于我们不会对其修改,故此处不需传指针
43 int  stack_len(sqStack s){
44     return (s.top - s.base); //返回数据的个数    
45 }
46 
47 int main(void){
48     ElemType c;
49     sqStack s;
50     int len = 0, i = 0, sum_10 = 0;
51     int j = 0, sum_8 = 0,tmp_8 = 0;
52     
53     init_stack(&s);        //初始化栈
54     while(1){
55         printf("请输入二进制数,输入#符号表示结束,开头输入q/Q退出!\n");
56         scanf("%c",&c);    //按字符格式接收
57         if(c == 'q' || c == 'Q')
58             break;
59         while(c != '#'){
60             push(&s,c);        //入栈
61             scanf("%c",&c);
62         }
63         getchar();        //将回车从当前缓冲区去除,用户按下回车后结束
64         
65         len = stack_len(s);        //获取栈的当前容量
66         printf("栈的当前容量是: %d\n",len);
67 
68         for(i = 0; i<len ; i++){
69             pop(&s, &c);  //传值使用引用方式
70             sum_10 =(int)( sum_10 + (c-48) * pow(2 , i));    //将ASCII转换为整形
71 
72             tmp_8 =(int)( tmp_8 + (c-48) * pow(2 , i%3));    //将ASCII转换为整形
73 
74             //printf("%d  %d\n",i%4,tmp_8);
75             if(i%3 == 2){        
76                 sum_8 += (int)(tmp_8 * pow(10 , (j++)));
77                 tmp_8 = 0;
78             }    
79         }
80         if(tmp_8 != 0){
81             sum_8 += (int)(tmp_8 * pow(10 , (j++)));
82             tmp_8 = 0;
83             j = 0;
84         }
85         printf("转换为十进制数是: %d 八进制数: 0%d\n",sum_10,sum_8);
86         sum_10 = 0;
87         sum_8 = 0;
88         j = 0;
89     }
90     return 0;
91 }

 

 

posted on 2015-04-05 12:12  Lover雪儿  阅读(854)  评论(0编辑  收藏  举报