最近从网上看到一些进制间转换的题目。对于这样的问题我尝试了使用栈来实现,实现了十进制转二进制、八进制、十六进制等其他进制转换方式。根据栈先进后出的特性,符合十进制转其他进制采用循环相除取余,然后反向输出。以下是我的代码,有更好地方式可以讨论一下:
1 #include <stdio.h>
2 #include <stdbool.h>
3
4 #define MAX 12
5 static char stack[MAX];
6 int top = 0;
7 int Binary_conversion(int num, int bit);
8
9 void push(char ch);
10 char pop();
11 bool is_empty();
12 bool is_full();
13
14 int main(void)
15 {
16 int num, bit;
17 while (1)
18 {
19 printf("Please input an integer number(input a negative number to quit):\n");
20 scanf("%d", &num);
21 if (num <= 0) /* exit the while(1) */
22 break;
23 printf("Please input the binary(input a negative number to quit): \n");
24 scanf("%d", &bit);
25 if (bit <= 0) /* exit the while(1) */
26 break;
27 Binary_conversion(num, bit);
28 if (is_full())
29 return -1;
30 #if 0
31 if (bit == 2)
32 {
33 printf("Convert into 2 binary: ");
34 while (!is_empty())
35 pop();
36 }
37 if (bit == 8)
38 {
39 printf("Convert into 8 binary:o");
40 while (!is_empty())
41 pop();
42 }
43
44 if (bit == 16)
45 {
46 printf("Convert into 16 binary:#");
47 while (!is_empty())
48 pop();
49 }
50 #else
51 switch(bit)
52 {
53 case 2: printf("Convert into 2 binary: ");
54 while (!(is_empty()))
55 printf("%c", pop());
56 putchar('\n');
57 break;
58 case 8: printf("Convert into 8 binary:o");
59 while (!is_empty())
60 printf("%c", pop());
61 putchar('\n');
62 break;
63 case 16: printf("Convert into 16 binary:#");
64 while (!is_empty())
65 printf("%c", pop());
66 putchar('\n');
67 break;
68 default:
69 while (!is_empty())
70 printf("%c", pop());
71 putchar('\n');
72 break;
73 }
74 #endif
75 }
76
77 return 0;
78 }
79
80 int Binary_conversion(int num, int bit)
81 {
82 int rt;
83 while (num != 0)
84 {
85 rt = num % bit;
86 if (rt < 10)
87 push(rt+'0');
88 else
89 push(rt+'A' - 10);
90
91 num = num / bit;
92 }
93
94
95 return 1;
96 }
97
98 /*
99 * Push a data to the stack.
100 */
101 void push(char ch)
102 {
103 stack[top++] = ch;
104 }
105 /*
106 * Pop a data from the stack.
107 */
108 char pop(void)
109 {
110 return stack[--top];
111 }
112
113 bool is_empty(void)
114 {
115 if (top == 0)
116 return true;
117 else
108 char pop(void)
109 {
110 return stack[--top];
111 }
112
113 bool is_empty(void)
114 {
115 if (top == 0)
116 return true;
117 else
118 return false;
119 }
120
121 bool is_full(void)
122 {
123 if (top == MAX)
124 return true;
125 else
126 return false;
127 }