#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 1024
typedef int ElemType;
typedef struct SqStack
{
ElemType data[MAXSIZE];
int top;
}SqStack;
//初始化
SqStack* InitStack()
{
SqStack* S;
S = (SqStack*)malloc(sizeof(SqStack));
if (S == NULL)
return S;
S->top = -1;
return S;
}
//判断栈是否为空
int EmptyStack(SqStack* S)
{
if (S->top == -1)
return 1;
else
return 0;
}
//入栈
int PushStack(SqStack* S, ElemType x)
{
if (S->top >= MAXSIZE - 1)
return 0;
S->top++;
S->data[S->top] = x;
return 1;
}
//出栈
int PopStack(SqStack* S, ElemType* x)
{
if (S->top == -1)
return 0;
else
{
S->top--;
*x = S->data[S->top + 1];
return 1;
}
}
//十进制转换为二进制
void zhuanhuan2(int N)
{
int x;
SqStack* S = InitStack();
while (N > 0)
{
PushStack(S, N % 2);
N = N / 2;
}
while (!EmptyStack(S))
{
PopStack(S, &x);
printf("%d", x);
}
}
//十进制转换为八进制
void zhuanhuan8(int M)
{
int x;
SqStack* S = InitStack();
while (M > 0)
{
PushStack(S, M % 8);
M= M / 8;
}
while (!EmptyStack(S))
{
PopStack(S, &x);
printf("%d", x);
}
}
//十进制转换为十六进制
void zhuanhuan16(int D)
{
int x;
SqStack* S = InitStack();
while (D > 0)
{
PushStack(S, D % 16);
D = D / 16;
}
while (!EmptyStack(S))
{
PopStack(S, &x);
switch (x)
{
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;
case 15:
printf("F");
break;
default:
printf("%d", x);
break;
}
}
}
int main()
{
int N,M,D;
printf("请输入你要转换的十进制数:\n");
scanf_s("%d", &N);
printf("其对应的二进制数为:\n");
zhuanhuan2(N);
printf("\n");
printf("请输入你要转换的十进制数:\n");
scanf_s("%d", &M);
printf("其对应的八进制数为:\n");
zhuanhuan8(M);
printf("\n");
printf("请输入你要转换的十进制数:\n");
scanf_s("%d", &D);
printf("其对应的十六进制数为:\n");
zhuanhuan16(D);
printf("\n");
return 0;
}
试运行结果:
欢迎大家指出问题。