用c语言利用栈实现输入十进制数将它转化为八进制
时间: 2024-03-17 09:43:13 浏览: 75
好的,下面是用C语言实现的栈转换十进制为八进制的代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
struct Stack {
int top;
int data[MAX_SIZE];
};
void initStack(struct Stack *s) {
s->top = -1;
}
void push(struct Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow!");
return;
}
s->top++;
s->data[s->top] = x;
}
int pop(struct Stack *s) {
if (s->top == -1) {
printf("Stack underflow!");
return -1;
}
int x = s->data[s->top];
s->top--;
return x;
}
int isEmpty(struct Stack *s) {
return s->top == -1;
}
int main() {
int decimal_num;
printf("Enter a decimal number: ");
scanf("%d", &decimal_num);
struct Stack s;
initStack(&s);
while (decimal_num > 0) {
int remainder = decimal_num % 8;
push(&s, remainder);
decimal_num /= 8;
}
printf("The octal number is: ");
while (!isEmpty(&s)) {
int digit = pop(&s);
printf("%d", digit);
}
return 0;
}
```
运行结果为:
```
Enter a decimal number: 123
The octal number is: 173
```
这个程序使用了一个结构体来定义栈,并实现了初始化、入栈、出栈、判断栈是否为空等基本操作。在主函数中,我们先输入一个十进制数,然后用栈来存储每次除以8后的余数,最后再把余数弹出栈,输出八进制数。
阅读全文