将十进制数num转换为r进制数,其转换方法为辗转相除法,要求用链栈实现。

步骤:程序中设计了四个函数:

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);
}




  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值