栈的应用--数制转换(十进制数转换为二进制,八进制,十六进制)

#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;
}

试运行结果:

 欢迎大家指出问题。

  • 9
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值