C语言—数制转换

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 100		//存储空间初始分配量
#define STACKINITCREMENT 10		//存储空间分配增量

typedef	int SElemType;
typedef struct {
	SElemType *base;	//栈底指针-空栈时为 NULL 
	SElemType *top;		//栈顶指针 
	int	stacksize;		//当前已分配的存储空间 
}SqStack;

void	InitStack(SqStack &S) {		//构造一个空栈 
	S.base = (SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));
	if(!S.base) {
		printf("构造栈失败,程序退出!");
		exit(!0);
	}
	S.top = S.base;		//栈顶指针指向栈底 
	S.stacksize = STACK_INIT_SIZE;	//栈当前的长度
}

void	GetTop(SqStack S,SElemType &sum) {	//获取栈顶元素 
	if(S.top == S.base) {
		printf("空栈,获取无效,程序退出!");
		exit(!0);
	} 
	sum = *(S.top -1);
	printf("\n转换为八进制后元素为:%d\n",sum);
}

void	Push(SqStack &S,SElemType e,SElemType sum) {	//插入元素 
	if(S.top - S.base >= S.stacksize) {	//如栈满,则扩展栈的空间 
		S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINITCREMENT)*sizeof(SElemType));
		if(!S.base) {
			printf("空间扩展失败,程序退出!");
			exit(!0);
		}
		S.top = S.base + S.stacksize;
		S.stacksize += STACKINITCREMENT;
	}
	int a,i = 0;
	sum = 0;
	printf("请输入一个整数:");
	scanf("%d",&e);
	while(e) {
		a=e%8;
		e=e/8;
		sum += a*pow(10,i);
		i++;
	} 
	*S.top++ = sum;
}

int main() {
	SqStack S;
	SElemType e,sum;
	InitStack(S);		//创建一个栈并
	Push(S,e,sum);			//入栈操作 
	GetTop(S,sum);		//获取栈顶元素 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Long_UP/article/details/121767046