内容:
将十进制整数num转换为r进制数,其转换方法为辗转相除法,要求用链栈实现
算法分析
- 本题要完成的是将十进制整数num转化为r进制数,其转换方法为辗转相除法,要求用到链栈结构。程序设计中要用到栈的基本操作,分别用不同的函数分别来实现栈的入栈,判断栈空和出栈操作。主函数有两个输入,即输入待转化的数和要转化的进制,函数Convert算法思想为:对待转换的数先判断正负,用判断语句分别实现正数与负数的转化。具体转化的方法为辗转相除法,然后将所得到的数字放入栈中,通过栈的先进后出原则输出即可得到进制转换的结果
概要设计
函数 |
函数Push(linkstack *top,int x) int 函数Empty(linkstack top) int 函数Pop(linkstack *top,int *x) int 函数Convert(int num,int mode) void |
代码
目录
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int date;
node* next;
}*linkstack;
int Push(linkstack *top,int x)//入栈,将输入数字x放入栈顶top
{
linkstack s = (linkstack)malloc(sizeof(struct node));//创建新的结点来进行入栈
if (s == NULL)
return 0;
s->date = x;//将数字放入节点中
s->next = (*top);//将结点放入到栈顶
*top = s;
return 1;
}
int Empty(linkstack top)//判断是否为空
{
if (top == NULL)
return 1;//说明栈为空
return 0;//否则不为空
}
int Pop(linkstack* top, int* x)//出栈,每次出栈顶的值
{
if (top != NULL)
{
linkstack p = *top;
(*x) = (*top)->date;
(*top) = (*top)->next;
free(p);
return 1;
}
return 0;
}
void Convert(int num, int mode)
{
int h;
linkstack top = NULL;
printf("转化结果为");
if (num > 0)//当num大于零时
{
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)//当num小于0时,将num乘以负一然后再求值再加上“-”然后与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);//当输入的num为0时直接输出0
}
void main()
{
int num, mode;
printf("\n请输入要转化的数字:");
scanf_s("%d",&num);
printf("\n输入要转化的进制:");
scanf_s("%d",&mode);
Convert(num,mode);
}