编程基于栈的操作实现将任意一个非负十进制数,打印输出 与其等值的八进制数C语言
时间: 2023-05-25 10:05:55 浏览: 69
用栈实现数制转换 c语言
#include <stdio.h>
#include <stdlib.h>
#define MaxStackSize 100
typedef struct {
int data[MaxStackSize];
int top;
} Stack;
Stack* InitStack(){
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
return s;
}
int IsEmpty(Stack* s){
return s->top == -1;
}
int IsFull(Stack* s){
return s->top == MaxStackSize - 1;
}
void Push(Stack* s, int x){
if(IsFull(s)){
printf("Stack overflow\n");
return;
}
s->data[++s->top] = x;
}
int Pop(Stack* s){
if(IsEmpty(s)){
printf("Stack underflow\n");
return -1;
}
int x = s->data[s->top--];
return x;
}
void DestroyStack(Stack* s){
free(s);
}
void DecimalToOctal(int n){
Stack* s = InitStack();
while(n > 0){
Push(s, n % 8);
n /= 8;
}
printf("Octal: ");
while(!IsEmpty(s)){
printf("%d", Pop(s));
}
DestroyStack(s);
}
int main(){
int n;
printf("Enter a non-negative decimal integer: ");
scanf("%d", &n);
if(n < 0){
printf("Error: The input number must be non-negative.\n");
return 0;
}
DecimalToOctal(n);
return 0;
}
阅读全文