利用栈实现十进制转八进制c++
时间: 2023-11-30 14:04:34 浏览: 92
用栈实现十进制转换为八进制
可以这样实现:
#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 push(Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("stack overflow\n");
return 0;
}
s->top++;
s->data[s->top] = x;
return 1;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("stack underflow\n");
return 0;
}
int x = s->data[s->top];
s->top--;
return x;
}
int is_empty(Stack *s) {
return s->top == -1;
}
void convert(int n) {
Stack s;
init(&s);
while (n != 0) {
push(&s, n % 8);
n /= 8;
}
while (!is_empty(&s)) {
printf("%d", pop(&s));
}
}
int main() {
int n;
scanf("%d", &n);
convert(n);
printf("\n");
return 0;
}
阅读全文