利用栈(以顺序栈作存储结构)实现进制转换。给定一个十进制整数,编程将该数以八进制形式输出。C++版
时间: 2023-10-29 21:05:29 浏览: 99
以下是利用栈实现十进制转八进制的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100 // 栈的最大容量
typedef struct {
int top; // 栈顶指针
int data[STACK_SIZE]; // 栈的数据域
} SqStack;
// 初始化栈
void InitStack(SqStack *s) {
s->top = -1;
}
// 判断栈是否为空
int IsEmpty(SqStack *s) {
return s->top == -1;
}
// 判断栈是否已满
int IsFull(SqStack *s) {
return s->top == STACK_SIZE - 1;
}
// 入栈
int Push(SqStack *s, int x) {
if (IsFull(s)) {
return 0; // 栈已满,入栈失败
} else {
s->data[++s->top] = x;
return 1; // 入栈成功
}
}
// 出栈
int Pop(SqStack *s) {
if (IsEmpty(s)) {
return -1; // 栈已空,出栈失败
} else {
return s->data[s->top--];
}
}
// 十进制转八进制
void DecToOct(int dec) {
SqStack s;
InitStack(&s); // 初始化栈
while (dec > 0) {
Push(&s, dec % 8); // 将余数入栈
dec /= 8; // 更新被除数
}
printf("转换结果为:");
while (!IsEmpty(&s)) {
printf("%d", Pop(&s)); // 依次出栈并打印
}
printf("\n");
}
int main() {
int dec;
printf("请输入一个十进制整数:");
scanf("%d", &dec);
DecToOct(dec);
return 0;
}
```
以上代码中,我们定义了一个顺序栈(`SqStack`),并实现了栈的基本操作(`InitStack`、`IsEmpty`、`IsFull`、`Push`、`Pop`),然后利用栈实现了十进制转八进制的功能(`DecToOct`)。在 `DecToOct` 函数中,我们采用了栈的思想,将每次除以 8 的余数入栈,最后再依次出栈并打印即可得到转换结果。
相关推荐
![](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)