步骤:程序中设计了四个函数:
1.函数Push()用于初始化一个顺序栈
2.函数Empty()用于实现栈的判空操作
3.函数Pop()用于实现元素的出栈操作
4.函数Convert()用于实现数制转换算法
算法分析:对待转换的数先判断正负,通过if...else...算法分别实现正数和负数的转化,转换的思想利用了算数运算中的取余和取整操作,借助栈先进后出的操作,进行辗转相除来实现。
流程图如下:
源码如下:
/*author:雷桂艺
time:2021年12月6日17:12
version:1.0
description:程序中设计了四个函数:
1.函数Push()用于初始化一个顺序栈
2.函数Empty()用于实现栈的判空操作
3.函数Pop()用于实现元素的出栈操作
4.函数Convert()用于实现数制转换算法
Convert算法思想:对待转换的数先判断正负,通过if...else...算法分别实现正数和负数的转化,转换的思想利用了算数运算中的取余和取整操作,借助栈的操作,进行辗转相除来实现。
*/
#include "stdafx.h"
#include<stdio.h>
#include<conio.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);
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;
if (h >= 10)
{
h = h - 10 + 'A';
}
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_s("%d", &num);
printf("输入要转化的进制:");
scanf_s("%d", &mode);
Convert(num, mode);
}