3.十进制转八进制
- 需求分析:
输入十进制数据将其转化为八进制
思想:利用栈实现,每次除八取模的余数放入栈中,再依次出栈,得到的结果即为转化后的八进制数 - 概要设计:
- 抽象数据结构:
ADT{
InitStack(SqStack& S) //初始化栈S
Push(SqStack& S, ElemType e) //入栈
Pop(SqStack& S, ElemType& e) //出栈
DectoOct(int num,SqStack &S,int& a) //十进制转八进制
}
- 程序用到的函数及层次关系:
main{
InitStack()
DectoOct(int num,SqStack &S,int& a){Push()
Pop()
}}
- 主程序流程:
输入十进制数据–>输出八进制数据–>存储到整形变量a中
- 详细设计:
- 定义顺序栈的基本数据结构:
#define maxsize 100
typedef int Status;
typedef int ElemType;
typedef struct {//顺序栈数据结构
ElemType* base;
ElemType* top;
int stacksize;
}SqStack;
- 定义栈的初始化函数:
Status InitStack(SqStack& S) {//初始化栈
S.base = (ElemType*)malloc(maxsize * sizeof(ElemType));
if (!S.base) return 0;
S.top = S.base;
S.stacksize = maxsize;
}
- 定义入栈函数:
Status Push(SqStack& S, ElemType e) {//入栈
if (S.top-S.base==S.stacksize) return 0;
*(S.top++) = e;
return 1;
}
- 定义十进制转化为八进制的函数:
将输入的数除八取模依次入栈,再依次出栈,用a接受值,并依次输出,若超出栈容量,提示需扩充栈的容量
void DectoOct(int num,SqStack &S,int& a) {//十进制转换八进制
int n = num;
int m,e;
while (n > 0) {
m = n % 8;
if (!Push(S, m)) {
printf("需扩大栈的容量!");
return;
}
n /= 8;
}
int k = S.top - S.base;
printf("八进制表示为:");
for (int i = 1; i <= k; i++) {
Pop(S, e);
a = 10*a + e;
printf("%d", e);
}
printf("\n");
}void DectoOct(int num,SqStack &S,int& a) {//十进制转换八进制
int n = num;
int m,e;
while (n > 0) {
m = n % 8;
if (!Push(S, m)) {
printf("需扩大栈的容量!");
return;
}
n /= 8;
}
int k = S.top - S.base;
printf("八进制表示为:");
for (int i = 1; i <= k; i++) {
Pop(S, e);
a = 10*a + e;
printf("%d", e);
}
printf("\n");
printf("a值为:%d", a);
}
- 完整代码:
#include <cstdio>
#include <cstdlib>
#define maxsize 100
typedef int Status;
typedef int ElemType;
typedef struct {//顺序栈数据结构
ElemType* base;
ElemType* top;
int stacksize;
}SqStack;
Status InitStack(SqStack& S) {//初始化栈
S.base = (ElemType*)malloc(maxsize * sizeof(ElemType));
if (!S.base) return 0;
S.top = S.base;
S.stacksize = maxsize;
}
Status Push(SqStack& S, ElemType e) {//入栈
if (S.top - S.base == S.stacksize) return 0;
*(S.top++) = e;
return 1;
}
Status Pop(SqStack& S, ElemType& e) {//出栈
if (S.top == S.base) return 0;
e = *(--S.top);
return 1;
}
void DectoOct(int num,SqStack &S,int& a) {//十进制转换八进制
int n = num;
int m,e;
while (n > 0) {
m = n % 8;
if (!Push(S, m)) {
printf("需扩大栈的容量!");
return;
}
n /= 8;
}
int k = S.top - S.base;
printf("八进制表示为:");
for (int i = 1; i <= k; i++) {
Pop(S, e);
a = 10*a + e;
printf("%d", e);
}
printf("\n");
printf("a值为:%d", a);
}
int main() {
int q;
int a=0;//存储得到的八进制数的值
SqStack S;
InitStack(S);
printf("请输入十进制数:");
scanf_s("%d", &q);
DectoOct(q, S,a);
}