数制转换
算法描述:
对于输入的任意一个非负十进制整数,打印输出与其等值的八进制数。
由于上述计算过程是从低位到高位顺序产生八进制数的各个数位,而打印输出,一般来说应从高位到低位进行,恰好和计算过程相反。因此,若将计算过程中得到的八进制数的各位顺序进栈,则按出栈序列打印输出的即为与输入对应的八进制数。
代码实现:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
#define ERROR 0
#define OK 1
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];//为顺序栈分配最大容量的内存
int top; //指向栈顶
}SqStack;
void Initstack(SqStack &S)
{
if(!S.data) exit(-1);
S.top = 0;
}
Status Push(SqStack &S,ElemType e)
{
if(S.top==MAXSIZE) return ERROR;
S.data[S.top++] = e;
return OK;
}
Status Pop(SqStack &S)
{
if(S.top<=0) return ERROR;
S.top--;
return OK;
}
void getTop(SqStack S,ElemType &e)
{
if(S.top==0) printf("栈空了!!");
e = S.data[S.top-1];
}
void Convertion(SqStack &S)
{
int n,r;
printf("输入要转换进制的数:\n");
scanf("%d",&n);
printf("输入要转换的进制:\n");
scanf("%d",&r);
while(n)
{
Push(S,n%r);
n/=r;
}
while(S.top)
{
ElemType e;
getTop(S,e);
Pop(S);
printf("%d",e);
}
printf("\n");
}
void traverse(SqStack S)
{
printf("进制转换结果:\n");
for(int i=S.top-1;i>=0;i--)
{
printf("%d",S.data[i]);
}
printf("\n");
}
int main()
{
SqStack S;
Initstack(S);
Convertion(S);
//我看了几个博客,都是用上面的方法,下面这个也可以
//traverse(S);//这两个函数只能用一个
return 0;
}