2022年9月19,利用顺序栈完成进制转换

这里使用栈的特性,FILO《先进后出》完成进制转换余数的逆序
中间考虑输入的格式问题(比如进制为0,或输入为字母的情况屏蔽掉)
在考虑负数的转换,采用了abs函数求绝对值

main.c

#include<stdio.h>
#include<stdlib.h>
#include"DecimalConversion.h"
int main(int argc, const char *argv[])
{
	SeqStack p = stack_create();
	int D,num;
	if(NULL == p)
	{
		return -1;
	}
	printf("请输入要进行进制转换的整数:");
	while(scanf("%d",&num) != 1 || num == 0)
	{
		while(getchar() != '\n');
		printf("\t\t请重新输入:");
	}
	printf("请输入要进行转换的进制:");
	while(scanf("%d",&D) != 1 || D <= 0)
	{
		while(getchar() != '\n');
		printf("\t\t请重新输入:");
	}
	//入栈函数
	char c = num>0?'+':'-';
	printf("\t\t%d的%d进制表示法是:%c",num,D,c);
	num = abs(num);
	while(num != 0)
	{
		push_stack(p,num%D);
		num /= D;
	}
	//出栈函数
	while(p->top>=0)
	{
	pull_stack(p);
	}
	printf("\n");
	return 0;
}

DecimalConversion.h

#ifndef __DECIMALCONVERSION_H__
#define __DECIMALCONVERSION_H__
#define MAX 32
typedef int datatype;
typedef struct {
	datatype data[MAX];
	int top;
}Node,*SeqStack;
//创建函数
SeqStack stack_create();
//判空函数
int isempty(SeqStack);
//判满函数
int isfull(SeqStack);
//入栈函数
int push_stack(SeqStack,datatype);
//遍历函数
void show_stack(SeqStack);
//出栈函数
int pull_stack(SeqStack);
//销毁函数
int destory_stack(SeqStack);
#endif

DecimalConversion.c

#include<stdio.h>
#include<stdlib.h>
#include"DecimalConversion.h"

//创建函数
SeqStack stack_create()
{
	//申请空间
	SeqStack p = (SeqStack)malloc(sizeof(Node));
	if(NULL == p)
	{
		printf("\t\t%s 申请顺序栈失败\n",__FUNCTION__);
		return NULL;
	}
	p->top = -1;//初始化top从-1开始;
	return p;
}
//判空函数
int isempty(SeqStack p)
{
	if(NULL == p)
	{
		return -1;
	}
	//判断栈区是不是空,主要是看栈顶的位置
	return p->top == -1;
}
//判满函数
int isfull(SeqStack p)
{
	if(NULL == p)
	{
		return -1;
	}
	//判断栈区是不是空,主要看栈顶下标是不是数组最大下标;
	return p->top == MAX-1;

}
//入栈函数
int push_stack(SeqStack p,datatype da)
{
	if(NULL == p || isfull(p))
	{
		printf("\t\t%s 栈不存在或已满\n",__FUNCTION__);
		return -1;
	}
	//入栈,先加下标,再赋值
	p->top++;
	p->data[p->top] = da;
	return 0;
}
//遍历函数
void show_stack(SeqStack p)
{
	if(NULL == p||isempty(p))
	{
		printf("\t\t%s 栈不存在或已空\n",__FUNCTION__);
		return ;
	}
	for(int i=p->top;i>=0;i--)
	{
		printf("%6d",p->data[i]);
	}
	printf("\n\t\t%s 遍历完成\n",__FUNCTION__);
}
//出栈函数
int pull_stack(SeqStack p)
{
	if(NULL ==p || isempty(p))
	{
		printf("\t\t%s 栈不存在或已空\n",__FUNCTION__);
		return -1;
	}
	int out = p->data[p->top];
	p->top--;
	//	printf("\t\t%s 出栈成功\n",__FUNCTION__);
	printf("%d",out);
	return out;
}
//销毁函数
int destory_stack(SeqStack p)
{
	if(NULL == p)
	{
		return -1;
	}
	free(p);
	p = NULL;
	printf("\t\t%s 销毁成功\n",__FUNCTION__);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值