将十进制整数num转换为r进制数

内容:

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

算法分析

  1. 本题要完成的是将十进制整数num转化为r进制数,其转换方法为辗转相除法,要求用到链栈结构。程序设计中要用到栈的基本操作,分别用不同的函数分别来实现栈的入栈,判断栈空和出栈操作。主函数有两个输入,即输入待转化的数和要转化的进制,函数Convert算法思想为:对待转换的数先判断正负,用判断语句分别实现正数与负数的转化。具体转化的方法为辗转相除法,然后将所得到的数字放入栈中,通过栈的先进后出原则输出即可得到进制转换的结果

概要设计 

函数

  函数Pushlinkstack *top,int x) int

  函数Emptylinkstack top) int

  函数Poplinkstack *top,int *xint

  函数Convertint 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);
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值