生活随笔
收集整理的這篇文章主要介紹了
二进制转十进制-栈的方式实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
二進制轉十進制實現
注意因為使用到了math.h中的函數,編譯的時候需要連接數據函數庫,即 -lm
#include <stdio.h>
#include <stdlib.h>
#include <math.h>#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10typedef char ElemType
;
typedef struct
{ElemType
*base
;ElemType
*top
;int stackSize
;
}sqStack
;void InitStack(sqStack
*s
);void Push(sqStack
*s
, ElemType e
);void Pop(sqStack
*s
, ElemType
*e
);int StackLen(sqStack s
);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
, (s
->stackSize
+ STACKINCREMENT
) * sizeof(ElemType
));if( !s
->base
){exit(0);}}*(s
->top
) = e
;s
->top
++;
}void Pop(sqStack
*s
, ElemType
*e
)
{if( s
->top
== s
->base
){return;}*e
= *--(s
->top
);
}int StackLen(sqStack s
)
{return (s
.top
- s
.base
);
}int main()
{ElemType c
;sqStack s
;int len
, i
, sum
= 0;InitStack(&s
);printf("請輸入二進制數,輸入#符號表示結束!\n");scanf("%c", &c
);while( c
!= '#' ){Push(&s
, c
);getchar(); scanf("%c", &c
);}len
= StackLen(s
);printf("棧的當前容量是: %d\n", len
);for( i
=0; i
< len
; i
++ ){Pop(&s
, &c
);printf("%c\n", c
);sum
= sum
+ (c
-48) * pow(2, i
);}printf("轉化為十進制數是: %d\n", sum
);return 0;
}
測試
andrew@andrew-Thurley:/work/linux-sys/data_structure_sqlite/src$ ./bin2dec
請輸入二進制數,輸入
1
0
1
0
1
0
1
0
1
0
棧的當前容量是: 10
0
1
0
1
0
1
0
1
0
1
轉化為十進制數是: 682
總結
以上是生活随笔為你收集整理的二进制转十进制-栈的方式实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。