⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 利用栈对进制转换.txt

📁 利用栈对进制转换
💻 TXT
字号:
// exp_2_1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"

typedef int status;
typedef int SElemType;
#define OVERFLOW -2
#define OK  1
#define ERROR  0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef struct
{
	SElemType *base;
	SElemType *top;
	int stacksize;
}SqStack;
status  InitStack(SqStack &S)  //初始化空栈S
{
	S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
	//if(!S.base) exit (OVERFLOW);
	S.top=S.base;
	S.stacksize=STACK_INIT_SIZE;
	return OK;
}
/*status GetTop(SqStack S,SElemType &e) //读取栈顶元素
{
	if(S.base==S.top) return ERROR;
	e=*(S.top-1);
	return OK;
}*/
status Push(SqStack &S,SElemType e)//插入
{
	if(S.top-S.base>=S.stacksize)
	{
		S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
		if(!S.base) exit(OVERFLOW);
		S.top=S.base+S.stacksize;
		S.stacksize+=STACKINCREMENT;
	}
	*S.top++=e;
	return OK;
}

status Pop(SqStack &S,SElemType &e) //出栈
{
	if(S.top==S.base)  return ERROR;
	e=*(--S.top);
	return OK;
}
status StackEmpty(SqStack S)
{
	if(S.top==S.base)
		return OK;
	else 
		return ERROR;
}

void conversion(SElemType e)
{
	SqStack S;
	InitStack(S);
	while(e)
	{
		Push(S,e%2);
		e=e/2;
	}
	while(!StackEmpty(S))
	{
		Pop(S,e);
		printf("%d",e);
	}
}

void  main(int argc, char* argv[])
{
	printf("\t\t欢迎进入栈的应用实验\n\n");
	printf("请输入要转换的十进制数:");
	SElemType N;
	scanf("%d",&N);
	printf("\n");
	while(N>=0)
	{
		conversion(N);
		printf("\n如需要继续转换请输入非负数字,否则输入负数退出本程序.\n");
		scanf("%d",&N);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -