写一C的代码,用到栈,把一个十进制数变成十六进制的数输出
- 提问者网友:不要迷恋哥
- 2021-04-21 01:08
- 五星知识达人网友:孤独的牧羊人
- 2021-04-21 02:43
只编了一个整数转换的
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct SqStack
{
int *base;
int *top;
int stacksize;
}
SqStack;
void InitStack(SqStack *S)
{
S->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
}
void Push(SqStack *S,int e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(int*)realloc(S->base,
(S->stacksize+STACKINCREMENT)*sizeof(int));
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top)=e;
S->top++;
}
int Pop(SqStack *S)
{
S->top --;
return *S->top;
}
int StackEmpty(SqStack *S)
{
if(S->top == S->base )
return 1;
else
return 0;
}
void conversion(int a)
{
SqStack S;int e;
InitStack(&S);
while(a)
{
Push(&S,a%16);
a=a/16;
}
while(!StackEmpty(&S))
{
e=Pop(&S);
switch (e)
{
case 10: printf("A");break;
case 11: printf("B");break;
case 12: printf("C");break;
case 13: printf("D");break;
case 14: printf("E");break;
default: printf("%d",e);
}
}
}
void main()
{
int a;
printf("输入个十进制数\n");
scanf("%d",&a);
printf("得到的为:\n");
conversion(a);
}