进制转换的核心模块
当e>9时,e+55输出A~F字符
void conversion( SeqStack* s, int n ,int m)
{
int e;
while (n)
{
Push_SeqStack(s,n%m); // "余数"入栈
n = n/m; //非零"商"继续运算
}
while (! Empty_SeqStack(s)) //栈非空,显示结果
{
Pop_SeqStack (s,&e);
if(e>9)
printf("%c",e+55);
else
printf("%d",e);
}
}
main函数
int main()
{
ElemType x;
int n;
int m;
SeqStack s;
Init_SeqStack(&s);
for(int i=0;i<3;i++)
{
printf("请输入十进制的值和要转换的位制:");
scanf("%d %d",&n,&m);
printf("%d进制结果为:",m);
conversion(&s,n,m); //调用二进制函数
printf("\n");
}
}
全部代码
#include<stdio.h>
#include<windows.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct Stack
{
ElemType data[MAXSIZE]; //栈空间
int top; //栈顶指示
}SeqStack;
void Init_SeqStack(SeqStack* s); //初始化顺序栈
int Empty_SeqStack(SeqStack* s); //判断顺序栈是否为空
int Push_SeqStack(SeqStack *s,ElemType x); //顺序栈入栈
void PrintStack(SeqStack *s); //输出顺序栈操作
int Pop_SeqStack(SeqStack* s,ElemType* x); //顺序栈出栈操作
void conversion( SeqStack* s, int n ,int m); //进制转换
int main()
{
ElemType x;
int n;
int m;
SeqStack s;
Init_SeqStack(&s);
for(int i=0;i<3;i++)
{
printf("请输入十进制的值和要转换的位制:");
scanf("%d %d",&n,&m);
printf("%d进制结果为:",m);
conversion(&s,n,m); //调用二进制函数
printf("\n");
}
}
/*======================
函数功能:顺序栈空栈
函数输入:顺序栈地址
函数输出:无
=======================*/
void Init_SeqStack(SeqStack* s)
{
s->top=-1;
}
/*======================
函数功能:判断顺序栈是否为空
函数输入:顺序栈地址
函数输出:1——栈空;2——栈非空
=======================*/
int Empty_SeqStack(SeqStack* s)
{
if(s->top==-1)
return 1;
else
return 0;
}
/*=======================
函数功能:顺序进栈操作
函数输入:数学栈地址,进栈元素值
函数输出:0——栈上溢,操作失败;1——操作正常
========================*/
int Push_SeqStack(SeqStack *s,ElemType x)
{
if(s->top==MAXSIZE-1) return 0;//栈满
else
{
s->top++;
s->data[s->top]=x;
/*printf("%4d入栈",s->data[s->top]);*/
}
return 1;
}
/*=======================
函数功能:顺序栈输出
函数输入:顺序栈地址
函数输出:无
========================*/
void PrintStack(SeqStack *s)
{
int i;
if(Empty_SeqStack(s)==1) //栈空不能输出
{
printf("顺序栈为空\n");
exit(1);
}
else
{
for(i=s->top;i>=0;i--)
printf("%4d",s->data[i]);
}
}
/*=======================
函数功能:顺序出栈操作
函数输入:顺序栈地址,出栈元素地址
函数输出:0——栈下溢,操作失败;1——操作正常
========================*/
int Pop_SeqStack(SeqStack*s,ElemType* x)
{
if(Empty_SeqStack(s)==1)return 0;
else
{
/*printf("%4d出栈",s->data[s->top]);*/
*x=s->data[s->top];
s->top--;
}
}
void conversion8( SeqStack* s, int n)
{
int e;
while (n)
{
Push_SeqStack(s,n%8); // "余数"入栈
n = n/8; //非零"商"继续运算
}
while (! Empty_SeqStack(s)) //栈非空,显示结果
{
Pop_SeqStack (s,&e);
printf("%d",e);
}
}
void conversion2( SeqStack* s, int n)
{
int e;
while (n)
{
Push_SeqStack(s,n%2); // "余数"入栈
n = n/2; //非零"商"继续运算
}
while (! Empty_SeqStack(s)) //栈非空,显示结果
{
Pop_SeqStack (s,&e);
printf("%d",e);
}
}
void conversion( SeqStack* s, int n ,int m)
{
int e;
while (n)
{
Push_SeqStack(s,n%m); // "余数"入栈
n = n/m; //非零"商"继续运算
}
while (! Empty_SeqStack(s)) //栈非空,显示结果
{
Pop_SeqStack (s,&e);
if(e>9)
printf("%c",e+55);
else
printf("%d",e);
}
}
结果:
看完点个赞!!!