设计算法,将十进制整数转换为八进制,在函数中输入数据并输出结果。 由于计算过程是从低位到高位顺序产生八进制数的各个数位,而打印输出,一般来说应从高位到低位进行,恰好
设计算法,将十进制整数转换为八进制,在函数中输入数据并输出结果。
由于计算过程是从低位到高位顺序产生八进制数的各个数位,而打印输出,一般来说应从高位到低位进行,恰好和计算过程相反。因此,若将计算过程中得到的八进制数的各位顺序进栈,则按出栈顺序打印输出的即为与输入对应的八进制数
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S->base)
exit(OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack *S,SElemType e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(SElemType*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S->base)
exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top++=e;
return OK;
}
Status StackEmpty(SqStack S)
{
return S.top==S.base;
}
Status Pop(SqStack *S,SElemType *e)
{
if(S->top==S->base)
return ERROR;
*e=*--S->top;
return OK;
}
void conversion()
{
SqStack S;
SElemType e;
InitStack(&S);
int n;
printf("请输入要转换的十进制数:");
scanf("%d",&n);
while(n)
{
Push(&S,n%8);
n=n/8;
}
printf("得到八进制数为:");
while(!StackEmpty(S))
{
Pop(&S,&e);
printf("%d",e);
}
}
int main()
{
conversion();
return 0;
}