1 #include2 3 #include 4 5 #define M 100 6 7 typedef int ElemType; 8 9 typedef struct { 10 11 ElemType data[M]; 12 13 int top; 14 15 }Stack; 16 17 void InitStack(Stack *s) { //初始化栈 18 19 s->top = -1; 20 21 } 22 23 int Push(Stack *s,ElemType e) { 24 25 if (s->top == M-1) { 26 27 printf("栈满\n"); 28 29 return 0; } 30 31 s->top++; 32 33 s->data[s->top]=e; return 1; 34 35 } 36 37 int Empty(Stack *s) { 38 39 return(s->top==-1); 40 41 } //判断是否为空 42 43 int Pop(Stack *s,ElemType *e) { 44 45 if(Empty(s)) { 46 47 printf("\n Stack is free"); 48 49 return 0; 50 51 } 52 53 *e=s->data[s->top]; 54 55 s->top--; 56 57 return 1; } //出栈 58 59 void Conversion(int N) { 60 61 int e; 62 63 Stack *s = (Stack *)malloc(sizeof(Stack)); 64 65 InitStack(s); 66 67 while(N){ 68 69 Push(s,N%2); 70 71 N=N/2; 72 73 } 74 75 while(!Empty(s)){ 76 77 Pop(s,&e); 78 79 printf("%d",e); 80 81 } 82 83 } 84 85 int main() { 86 87 int n,m; 88 89 while(1) { 90 91 printf("1:进行转换,2:退出\n"); 92 93 scanf("%d",&n); 94 95 switch(n) { 96 97 case 1: printf("请输入待转换的整数值: "); 98 99 scanf("%d",&m); 100 101 printf("转换为二进制值为: "); 102 103 Conversion(m); 104 105 printf("\n"); 106 107 break; 108 109 case 2: exit(0); 110 111 default: printf("error\n"); 112 113 } 114 115 } 116 117 }