在c语言中,利用栈完成一下操作,对于输入任何一个非负十进制整数,打印输出8进制整数
时间: 2023-10-06 15:09:09 浏览: 47
可以利用栈的后进先出的特点,将输入的十进制整数转换为8进制整数。具体实现过程如下:
1. 定义一个栈结构体,用于存储余数。
2. 从输入中读取一个十进制整数,将其不断除以8,将余数入栈,直到商为0。
3. 从栈中依次出栈,输出每个余数,即为8进制整数。
代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100
typedef struct {
int top; // 栈顶指针
int data[STACK_SIZE]; // 栈中元素
} 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 == STACK_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--];
}
int main() {
int n;
Stack s;
init(&s);
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n == 0) {
printf("0\n");
return 0;
}
// 将十进制整数转换为8进制整数
while (n != 0) {
push(&s, n % 8);
n /= 8;
}
// 输出8进制整数
printf("Octal integer: ");
while (!is_empty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
return 0;
}
```
例如,输入十进制整数37,输出8进制整数45。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)