读书人

输入十进制整数分别转换成2进制、8进制

发布时间: 2012-09-25 09:55:58 作者: rapoo

输入十进制整数分别转换成2进制、8进制、16进制数,并在屏幕上打印输出
数据结构,用链栈

[解决办法]
一下是我写的代码:仅供参考吧。
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: ");
20 scanf("%d", &num);
21 printf("Please input the binary: ");
22 scanf("%d", &bit);
23 Binary_conversion(num, bit);
24 if (is_full())
25 return -1;
26 #if 0
27 if (bit == 2)
28 {
29 printf("Convert into 2 binary: ");
30 while (!is_empty())
31 pop();
32 }
33 if (bit == 8)
34 {
35 printf("Convert into 8 binary:o");
36 while (!is_empty())
37 pop();
38 }
39
40 if (bit == 16)
41 {
42 printf("Convert into 16 binary:#");
43 while (!is_empty())
44 pop();
45 }
46 #else
47 switch(bit)
48 {
49 case 2: printf("Convert into 2 binary: ");
50 while (!(is_empty()))
51 printf("%c", pop());
52 putchar('\n');
53 break;
54 case 8: printf("Convert into 8 binary:o");
55 while (!is_empty())
56 printf("%c", pop());
57 putchar('\n');
58 break;
59 case 16: printf("Convert into 16 binary:#");
60 while (!is_empty())
61 printf("%c", pop());
62 putchar('\n');
63 break;
64 default:
65 while (!is_empty())
66 printf("%c", pop());
67 putchar('\n');
68 break;
69 }
70 if (num == -1) /* exit the while(1) */
71 break;
72 #endif
73 }
74
75 return 0;
76 }
77
78 int Binary_conversion(int num, int bit)
79 {
80 int rt;
81 while (num != 0)
82 {
83 rt = num % bit;
84 if (rt < 10)
85 push(rt+'0');
86 else
87 push(rt+'A' - 10);
88
89 num = num / bit;
90 }
91
92
93 return 1;
94 }
95
96 /*
97 * Push a data to the stack.
98 */
99 void push(char ch)
100 {
101 stack[top++] = ch;
102 }
103 /*
104 * Pop a data from the stack.
105 */
106 char pop(void)
107 {
108 return stack[--top];
109 }


110
111 bool is_empty(void)
112 {
113 if (top == 0)
114 return true;
115 else
116 return false;
117 }
118
119 bool is_full(void)
120 {
121 if (top == MAX)
122 return true;
123 else
124 return false;
125 }

读书人网 >C语言

热点推荐