用C语言实使用栈完成十进制转二八十六进制
时间: 2023-11-29 10:06:32 浏览: 97
以下是使用栈完成十进制转二八十六进制的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void init(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 overflow!\n");
exit(1);
}
s->data[++s->top] = value;
}
int pop(Stack* s) {
if (is_empty(s)) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top--];
}
void convert(int n, int base) {
Stack s;
init(&s);
while (n > 0) {
push(&s, n % base);
n /= base;
}
while (!is_empty(&s)) {
int digit = pop(&s);
if (digit < 10) {
printf("%d", digit);
} else {
printf("%c", 'A' + digit - 10);
}
}
}
int main() {
int n;
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("Binary: ");
convert(n, 2);
printf("\nOctal: ");
convert(n, 8);
printf("\nHexadecimal: ");
convert(n, 16);
printf("\n");
return 0;
}
```
这个程序首先定义了一个栈的结构体,包含一个整型数组和一个栈顶指针。然后定义了一些基本的栈操作函数,如初始化、判断是否为空、判断是否已满、入栈和出栈。接下来是一个转换函数,它将给定的十进制数转换为指定的进制,并将结果输出到屏幕上。最后,在主函数中读入一个十进制数,分别将其转换为二进制、八进制和十六进制,并输出结果。
需要注意的是,当栈满时,push函数会引发一个栈溢出错误,程序将退出。当栈为空时,pop函数会引发一个栈下溢错误,程序也将退出。这是为了避免在栈操作时发生不可预料的错误。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.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)