建立一个栈,输入输出功能,10进制数专为二进制,8进制数输出,基于c语言
时间: 2024-02-05 16:05:13 浏览: 56
好的,以下是一个基于 C 语言的栈的实现示例,实现了输入输出功能,并且可以将输入的十进制数转换为二进制数,输出的是八进制数:
```c
#include <stdio.h>
#define STACK_SIZE 20
struct Stack {
int top;
int items[STACK_SIZE];
};
void init_stack(struct Stack *s) {
s->top = -1;
}
int is_empty(struct Stack *s) {
return s->top == -1;
}
int is_full(struct Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(struct Stack *s, int item) {
if (is_full(s)) {
printf("Stack overflow!\n");
return;
}
s->items[++s->top] = item;
}
int pop(struct Stack *s) {
if (is_empty(s)) {
printf("Stack underflow!\n");
return -1;
}
return s->items[s->top--];
}
int peek(struct Stack *s) {
if (is_empty(s)) {
printf("Stack underflow!\n");
return -1;
}
return s->items[s->top];
}
void decimal_to_binary(int decimal) {
struct Stack s;
init_stack(&s);
while (decimal > 0) {
int remainder = decimal % 2;
push(&s, remainder);
decimal /= 2;
}
printf("Binary: ");
while (!is_empty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
void decimal_to_octal(int decimal) {
struct Stack s;
init_stack(&s);
while (decimal > 0) {
int remainder = decimal % 8;
push(&s, remainder);
decimal /= 8;
}
printf("Octal: ");
while (!is_empty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int decimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
decimal_to_octal(decimal);
return 0;
}
```
你可以通过以下命令编译和运行程序:
```
gcc stack.c -o stack
./stack
```
然后输入一个十进制数即可看到输出的二进制数和八进制数。
阅读全文