题目内容
将十进制整数num转换为r进制数,其转换方法为辗转相除法。要求用链栈实现。
- 算法设计
数制转换问题需要用到栈的基本操作,程序中用了三个函数分别实现链栈的入栈、判断栈空和出栈操作。主函数有两个输入,即输入待转化的数和要转化的进制,函数Convert算法思想为:对带转化的数先判断正负,用if...else语句分别实现正数和负数的转化,转换的思想是利用算数运算中的取余和取整操作,借助栈的操作,进行辗转相除来实现。
- 概要分析
本设计使用链栈来实现。
实现的是整数的转换。
程序中设计了四个函数:
函数Push()用来将元素入栈;
函数Empty()用来实现函数的判空操作;
函数Pop()用来实现函数的判空操作;
函数Convert()用来数制转换算法;
流程图
/********
@author:sy
@date:2021-10-14
@version:1.0
@Description:将十进制整数num转换为r进制数
********/
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node*next;
}*linkstack;
/*入栈*/
int Push(linkstack*top,datatype x)
{
linkstack s = (linkstack)malloc(sizeof(struct node));
if(s==NULL)
return 0;
s->data = x;
s->next = (*top); //把当前栈顶指针元素赋给插入结点的后继
(*top)=s; //把新结点赋给栈顶指针
return 1;
}
/*判空*/
int Empty(linkstack top)
{
if(top==NULL)
return 1;
return 0;
}
/*出栈*/
int Pop(linkstack*top,datatype*x)
{
if(top!=NULL) //如果栈不为空则将元素出栈
{
linkstack p=(*top);
(*x)=(*top)->data;
(*top)=(*top)->next; //栈顶指针下移一位
free(p); //释放p结点
return 1;
}
return 0;
}
/*将十进制整数化为任意进制数*/
void Convert(int num,int mode)
{
int h;
linkstack top=NULL;
printf("转换结果为:");
if(num>0)
{
while(num!=0)
{
h=num%mode;
Push(&top,h);
num=num/mode;
}
while(!Empty(top))
{
Pop(&top,&h);
printf("%d",h);
}
printf("\n");
}
else if(num<0)
{
printf("-");
num=num*(-1);
while(num!=0)
{
h=num%mode;
Push(&top,h);
num=num/mode;
}
while(!Empty(top))
{
Pop(&top,&h);
printf("%d",h);
}
printf("\n");
}
else
printf("%d\n",0);
}
int main()
{
int num,mode;
printf("\n 输入要转化的数:");
scanf("%d",&num);
printf("输入要转化进制:");
scanf("%d",&mode);
Convert(num,mode);
}
注:十进制整数转化为r进制(除r取余;逆序输出)
采用除r取余的方法,即将十进制数不断除以r取余数,直到尚为0,然后需要逆序输出