📄 十进制转十六进制(顺序栈).cpp
字号:
//程序运行成功。
#define Stack_Init_Size 100
#define StackIncrement 10
#define OVERFLOW -2
#include <stdio.h>
#include <stdlib.h>
typedef struct
{ int *base; /*栈构造前、销毁后base的值为NULL*/
int *top; /*栈顶指针*/
int stacksize; /*当前已分配的存储空间,以元素为单位*/
} SqStack;
void main()
{ void InitStack(SqStack &S);
void Push(SqStack &s, int e);
void Pop(SqStack &s, int &e);
SqStack s; unsigned n; int e; char c;
InitStack(s);
printf("请输入一个非负的十进制整数:\n");
scanf ("%u", &n);
while(n)
{ Push(s, n%16); /*将整数对16取余后的结果入栈*/
n=n/16; /*将整数对16整除*/
}
printf("转化成十六进制数为:\n");
while(!(s.top==s.base)) /*栈非空*/
{ Pop(s, e); /*将栈顶元素弹出*/
switch (e)
{ case 10:
c='A';printf("%c", c);break;
case 11:
c='B';printf("%c", c);break;
case 12:
c='C';printf("%c", c);break;
case 13:
c='D';printf("%c", c);break;
case 14:
c='E';printf("%c", c);break;
case 15:
c='F';printf("%c", c);break;
default:
printf("%d", e);break;
}
}
printf("\n");
}
void InitStack(SqStack &S)
{ S.base=(int*)malloc(Stack_Init_Size*sizeof(int)); /*分配栈空间*/
if(!S.base) printf("空间分配失败\n"), exit(OVERFLOW);
S.top=S.base; /*栈顶指针指向栈底, 即置为空栈*/
S.stacksize= Stack_Init_Size;
}
void Push(SqStack &s, int e)
{ int *l_temp;
if (s.top-s.base>=s.stacksize) /*栈满追加存储空间*/
{ l_temp=(int*)realloc(s.base,(s.stacksize+StackIncrement)*sizeof(int));
if (l_temp=0) printf("分配空间失败\n"), exit(OVERFLOW);
s.base=l_temp;
s.top=s.base+s.stacksize;
s.stacksize+=StackIncrement;
}
*(s.top++) = e;
}
void Pop(SqStack &s, int &e)
{ if (s.top==s.base) exit(OVERFLOW);
e=*(--s.top);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -