用栈实现10进制转换成8进制和2进制的代码,规定用c语言
时间: 2023-04-08 16:05:00 浏览: 51
以下是用栈实现10进制转换成8进制和2进制的代码,使用C语言:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} 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 == MAX_SIZE - 1;
}
void push(Stack *s, int x) {
if (is_full(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
void convert_to_binary(Stack *s, int n) {
while (n > 0) {
push(s, n % 2);
n /= 2;
}
}
void convert_to_octal(Stack *s, int n) {
while (n > 0) {
push(s, n % 8);
n /= 8;
}
}
int main() {
int n;
Stack s;
init(&s);
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("Binary: ");
convert_to_binary(&s, n);
while (!is_empty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
printf("Octal: ");
convert_to_octal(&s, n);
while (!is_empty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
return 0;
}