使用栈将用户输入的十进制数字转换为二进制,八进制,十六进制。
来源:每周上机题目!
特此鸣谢:鱼C_小甲鱼(B站UP主)
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 20 //定义我们首先申请的栈的空间
#define CREAT_SIZE 10 //若申请的空间不够,进行追加空间
typedef int ElemType;
typedef struct stack
{
int stacksize; //栈的容量
ElemType *base; //尾指针
ElemType *top; //头指针
}sqstack; //定义名称为sqstack的结构体
void init_stack(sqstack *s); //函数,初始化栈
void push_stack(sqstack *s, ElemType e); //函数,入栈
void pop_stack(sqstack *s, ElemType *e); //函数,出栈
void convert_two(sqstack *s, ElemType e); //函数,将十进制数字转换为二进制
void convert_eight(sqstack *s, ElemType e); //函数,将十进制数字转换为八进制
void convert_sixteen(sqstack *s, ElemType e); //函数,将十进制数字转换为十六进制
void init_stack(sqstack *s) //函数,初始化栈
{
s->base = (ElemType *)malloc(STACK_SIZE * sizeof(ElemType));
if(! s->base) //申请失败
{
exit(0);
}
s->top = s->base;
s->stacksize = STACK_SIZE;
}
void push_stack(sqstack *s, ElemType e) //函数,入栈
{
if(s->top - s->base >= s->stacksize) //如果栈的容量不够,导致溢出
{
s->base = (ElemType *)realloc(s->base, (s->stacksize + CREAT_SIZE) * sizeof(ElemType));//使用realloc函数增加容量
if(! s->base) //申请空间失败
{
exit(0);
}
}
*(s->top) = e; //对s->top这个指针指向的地址解引用,把e赋值给这个地址的值
s->top++; //指针逐步增加
}
void pop_stack(sqstack *s, ElemType *e) //函数,出栈
{
if(s->top == s->base) //栈尾指针和头指针指向相同的位置,栈内没有元素
{
exit(0);
}
*e = *--(s->top); //出栈,将头指针指向的地址的值给指针e,并且头指针向下移动
}
void convert_two(sqstack *s, ElemType e) //函数,将十进制数字转换为二进制
{
init_stack(s); //函数,初始化栈
while(e) //将转换的二进制入栈
{
push_stack(s, e % 2);
e = e / 2;
}
printf("转换后的二进制是:");
while(s->top != s->base) //栈内不为空时,将栈内元素出栈
{
pop_stack(s, &e);
printf("%d", e);
}
printf("\n");
}
void convert_eight(sqstack *s, ElemType e) //函数,将十进制数字转换为八进制
{
init_stack(s);
while(e)
{
push_stack(s, e % 8);
e = e / 8;
}
printf("转换后的八进制是:");
while(s->top != s->base)
{
pop_stack(s, &e);
printf("%d", e);
}
printf("\n");
}
void convert_sixteen(sqstack *s, ElemType e) //函数,将十进制数字转换为十六进制
{
init_stack(s);
while(e)
{
push_stack(s, e % 16);
e = e / 16;
}
printf("转换后的十六进制是:");
while(s->top != s->base)
{
pop_stack(s, &e);
if(e == 10)
printf("A");
else if(e == 11)
printf("B");
else if(e == 12)
printf("C");
else if(e ==13)
printf("D");
else if(e == 14)
printf("E");
else if(e == 15)
printf("F");
else printf("%d", e);
}
printf("\n");
}
int main(void)
{
ElemType c; //用户输入的数
sqstack s; //栈s
int z; //用户输入的需要转换的进制
int certain = 1;
int i = 1;
printf("请输入十进制数字,我们将会转换它的进制!输入数字0或者进制0则程序结束!\n");
printf("转换为二进制请输入2,八进制输入8!十六进制输入16!\n");
printf("\n");
while(certain)
{
printf("这是您的第%d次转换进制!\n", i++);
printf("请输入数字:");
scanf("%d", &c);
if(c != 0) //如果用户输入数字0,程序结束
{
printf("请选择进制:");
scanf("%d", &z);
if(z != 0) //如果用户输入进制0,程序结束
{
switch(z) //根据用户输入的进制数的不同来调用不同的函数
{
case 2:
convert_two(&s, c);
break;
case 8:
convert_eight(&s, c);
break;
case 16:
convert_sixteen(&s, c);
break;
}
printf("\n");
}
else
{
printf("\n程序结束,感谢您的使用!");
return 0;
}
}
else
{
printf("\n程序结束,感谢您的使用!");
return 0;
}
}
return 0;
}
运行结果如下: