编程基于栈的操作实现将任意一个非负十进制数,打印输出 与其等值的八进制数C语言
时间: 2023-05-25 14:06:01 浏览: 49
的实现代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
fprintf(stderr, "Stack is full\n");
exit(EXIT_FAILURE);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
fprintf(stderr, "Stack is empty\n");
exit(EXIT_FAILURE);
}
return s->data[s->top--];
}
void decimalToOctal(int decimal) {
Stack s;
init(&s);
do {
push(&s, decimal % 8);
decimal /= 8;
} while (decimal > 0);
printf("Octal equivalent is: ");
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int decimal;
printf("Enter a non-negative decimal number: ");
scanf("%d", &decimal);
if (decimal < 0) {
fprintf(stderr, "Invalid input\n");
exit(EXIT_FAILURE);
}
decimalToOctal(decimal);
return 0;
}
```