这里使用栈的特性,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;
}