资源描述
《数据结构》实验报告二
实验内容: 进制之间的转换
学号: 20105101132 姓名: 许丽敏
一、上机实验的问题和要求(需求分析):
[ 题目 ]将十进制数转换为其他进制。
二、程序设计的基本思想,原理和算法描述:
利用栈的基本操作实现进制间的转换。
三、调试和运行程序过程中产生的问题及采取的措施:
Conversion的使用
四、源程序及注释
[ 源程序 ] 程序名:实验二:进制间的转换.cpp
# include<stdio.h>
# include<malloc.h>
# define OK 1
# define ERROR 0
# define STACK_INIT_size 100
# define STACKINCREAMENT 10
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) return ERROR;
S.top=S.base;
S.stacksize=STACK_INIT_size;
return OK;
}
Status Push(SqStack &S,SElemType e){//插入元素e为新的栈顶元素
if(S.top-S.base>=S.stacksize){//栈满,另辟存储空间
S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREAMENT)*sizeof(SElemType));
if(!S.base) return ERROR;
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREAMENT;
}
*S.top++=e;
return OK;
}
Status Gettop(SqStack S,SElemType &e)
{
if(S.top=S.base) return ERROR;
e=*(S.top-1);
return OK;
}
int Stacklength(SqStack S)
{
return S.top-S.base;
}
void StackTrave(SqStack S)
{
while(S.top>S.base)
{
printf("%4d",*S.base);
S.base++;
}
printf("\n");
}
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}
Status StackEmpty(SqStack S){
if(S.base==S.top)
return OK;
return ERROR;
}
void conversion(){
int N,m;
SElemType e;
SqStack S;
InitStack(S);
printf("Please input the number:\n");
scanf("%d",&N);//输入一个非负的十进制整数N
printf("转换为几(2,8,16)进制:\n");
scanf("%d",&m);
while(N){
Push(S,N%m);
N=N/m;
}
printf("Please output the number\n");
while(!StackEmpty(S)){
Pop(S,e);
printf("%d",e);
}
printf("\n");
}
void main()
{
SqStack S;
SElemType e;
int i,n;
if(InitStack(S))
printf("Successful!\n");
printf("Please input the number:");
scanf("%d",&n);
printf("Please input the datas:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&e);
Push(S,e);
}
printf("栈中元素依次为:\n");
StackTrave(S);
printf("栈的长度为%d\n",Stacklength(S));
printf("栈顶元素为");
Gettop(S,e);
printf("%d",e);
printf("\n");
printf("Please output the datas:\n");
for(i=n;i>=1;i--)
{
Pop(S,e);
printf("%4d",e);
}
printf("\n");
conversion();
}五、运行结果
展开阅读全文