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

📄 数制转换.cpp

📁 简单的数制转换程序 简单的数制转换程序 简单的数制转换程序
💻 CPP
字号:
// 数制转换.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;

#define LEN 100


struct stack
{
	int *base;
	int *top;
	int stackSize;
};

Status initStack(stack &s);
Status push(stack &s,int e);
bool stackEmpty(stack &s);
Status pop(stack &s,int &e);
Status destoryStack(stack &s);

int toDec(char* num,int from,int len)
{
	int number = 0;          
	for(int i=0;i<len;i++)
		number = number * from + ( num[i] <= '9' ? num[i] - '0' : num[i] - 'A' + 10 );
	return number;
}

void main()
{
	int dec;
	int from;
	int to;
	int e;
	char num[] = {""};

	printf("Type in FROM:");
	scanf("%d",&from);
	printf("Type in TO:");
	scanf("%d",&to);
	printf("Type in number:");
	scanf("%s",num);
	dec = toDec(num,from,strlen(num));
	stack s;
	initStack(s);
	while(dec)
	{
		push(s,dec % to);
		dec = dec / to;
	}
	printf("Number from %d to %d is: ",from,to);
	while(!stackEmpty(s))
	{
		pop(s,e);
		printf("%c",e <= 9 ? e + '0' : e + 'A' - 10);
	}
	printf("\n");
	int stop;
	scanf("%d",&stop);
	destoryStack(s);
}


Status initStack(stack &s)						//init the stack
{
	s.base = (int*)malloc(LEN * sizeof(int));
	if(!s.base)
		exit(OVERFLOW);
	s.top = s.base;
	s.stackSize = LEN;
	return OK;
}


Status push(stack &s,int e)						//input node
{
	if(s.top - s.base >= s.stackSize)
	{
		s.base = (int*)realloc(s.base,(s.stackSize + 10) * sizeof(int));
		if(!s.base)
			exit(OVERFLOW);
		s.top = s.base + s.stackSize;
		s.stackSize += 10;
	}
	*s.top++ = e;
	return OK;
}


Status pop(stack &s,int &e)					//output node
{
	if(s.top == s.base)
		return ERROR;
	e= * --s.top;
	return OK;
}


bool stackEmpty(stack &s)				//judge empty
{
	bool flag = false;
	if(s.base == s.top)
		flag = true;
	return flag;
}

Status destoryStack(stack &s)           //destory stack
{
	s.top = NULL;
	s.stackSize = 0;
	free(s.base);
	s.base = NULL;
	return OK;
}

⌨️ 快捷键说明

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