C語言用棧實現(xiàn)十進制轉(zhuǎn)換為二進制的方法示例
更新時間:2017年06月05日 14:06:29 作者:PHP開發(fā)學(xué)習(xí)門戶
這篇文章主要介紹了C語言用棧實現(xiàn)十進制轉(zhuǎn)換為二進制的方法,結(jié)合實例形式分析了C語言棧的定義及進制轉(zhuǎn)換使用技巧,需要的朋友可以參考下
本文實例講述了C語言用棧實現(xiàn)十進制轉(zhuǎn)換為二進制的方法。分享給大家供大家參考,具體如下:
#include<stdio.h> #include<malloc.h> #include<math.h> #include<string.h> #include "process.h" #define SIZE 100 #define STACKINCREMENT 10 #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 typedef int Status; typedef struct { int a; } SElemType; typedef struct { SElemType *base; SElemType *top; int stacksize; } SqStack; SqStack S; //定義全局變量 Status InitStack(SqStack *S) { S->base=(SElemType *)malloc(SIZE*sizeof(SElemType)); if(!S->base) exit(OVERFLOW); S->top=S->base; S->stacksize=SIZE; return OK; } Status Push(SqStack *S,SElemType e) { if(S->top-S->base>=S->stacksize) { S->base=(SElemType *)malloc((S->stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S->base) exit(OVERFLOW); S->top=S->base+S->stacksize; S->stacksize+=STACKINCREMENT; } *S->top++=e; //printf("%dwww\n",*--S->top); return OK; } Status Stackempty(SqStack *S) { if(S->top==S->base) return TRUE; else return FALSE; } Status Pop(SqStack *S,SElemType *e) { if(S->top==S->base) return ERROR; *e=*--S->top; return OK; } Status DtoBTrans(int N,SqStack *S) { SElemType e; while(N) { e.a=N%2; Push(S,e); N=N/2; } while(!Stackempty(S)) { Pop(S,&e); printf("%d",e); } return OK; } void main() { int x; InitStack(&S); printf("請輸入十進制數(shù):"); scanf("%d",&x); DtoBTrans(x,&S); }
運行結(jié)果:
希望本文所述對大家C語言程序設(shè)計有所幫助。
相關(guān)文章
C++實現(xiàn)LeetCode(12.整數(shù)轉(zhuǎn)化成羅馬數(shù)字)
這篇文章主要介紹了C++實現(xiàn)LeetCode(12.整數(shù)轉(zhuǎn)化成羅馬數(shù)字),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07數(shù)據(jù)結(jié)構(gòu)用兩個棧實現(xiàn)一個隊列的實例
這篇文章主要介紹了C++語言數(shù)據(jù)結(jié)構(gòu)用兩個棧實現(xiàn)一個隊列的實例的相關(guān)資料,需要的朋友可以參考下2017-06-06