用栈实现任意进制转换c语言
时间: 2023-08-30 19:12:33 浏览: 70
好的,下面是用栈实现任意进制转换的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void init_stack(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int value) {
if (is_full(s)) {
printf("stack is full\n");
exit(1);
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("stack is empty\n");
exit(1);
}
int value = s->data[s->top];
s->top--;
return value;
}
void convert_base(int num, int base) {
Stack s;
init_stack(&s);
while (num != 0) {
int remainder = num % base;
push(&s, remainder);
num /= base;
}
printf("base %d: ", base);
while (!is_empty(&s)) {
int digit = pop(&s);
if (digit < 10) {
printf("%d", digit);
} else {
printf("%c", 'A' + digit - 10);
}
}
printf("\n");
}
int main() {
int num = 42;
convert_base(num, 2);
convert_base(num, 8);
convert_base(num, 16);
return 0;
}
```
代码中用栈来保存转换后的每一位数字,然后从栈中依次取出每一位数字并输出即可。其中,`convert_base`函数实现了将一个十进制数转换为任意进制的功能,`main`函数则演示了将一个十进制数转换为二进制、八进制、十六进制的过程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)