#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈顶指针
} SqStack;
void InitStack(SqStack *s); //初始化空栈
int StackEmpty(SqStack *s); //判空
int GetTop(SqStack *s, ElemType *e); //获得栈顶元素
int Push(SqStack *s, ElemType x); //进栈
int Pop(SqStack *s, ElemType *e); //出栈
void convert(SqStack *s, int N, int x); //十进制数N转x进制
int main()
{
unsigned X, N; //要转换成的进制数和要转换的数
SqStack s;
InitStack(&s); //初始化空栈
printf("输入要转换的十进制数:");
scanf("%d", &N);
printf("输入要转换为的进制数:");
scanf("%d", &X);
printf("十进制的%d转换为%d进制后为:\n", N, X);
convert(&s, N, X);
}
//栈的初始化
void InitStack(SqStack *s)
{
s->top = -1;
}
//判断栈是否为空,栈为空返回1,否则返回0
int StackEmpty(SqStack *s)
{ //补全代码
if (s->top == -1)
return 1;
return 0;
}
//取栈顶元素,将栈顶元素值返回给e
int GetTop(SqStack *s, ElemType *e)
{ //补全代码
while (1)
{
if (s->top == -1)
{
printf("输入有误,请重新输入\n");
}
else
{
*e = s->data[s->top];
return *e;
}
}
}
//将元素x进栈,元素进栈成功返回1,否则返回0
int Push(SqStack *s, ElemType x)
{ //补全代码
if (s->top == MaxSize - 1)
return 0;
else
{
s->top++;
s->data[s->top] = x;
return 1;
}
}
//将栈顶元素出栈并将其赋值给e,出栈成功返回1,否则返回0
int Pop(SqStack *s, ElemType *e)
{ //补全代码
if (s->top == -1)
return 0;
else
{
*e = GetTop(s, e);
s->top--;
return *e;
}
}
//十进制数的N转X进制
void convert(SqStack *s, int N, int X)
{ //补全代码
int z, y;
while (N > 0)
{
z = N % X; //余数存入z中
Push(s, z); //余数进栈
N /= X; //得到的商重新作为被除数
};
while (!StackEmpty(s))
{
Pop(s, &y); //输出存放在栈中的八进制数。
printf("%d", y);
}
printf("\n");
}