刚写的数制转换,已在VS上通过编译运行,代码如下:
#include "stdafx.h"
#include"stdio.h"
#include"stdlib.h"
#define OVERFLOW -1
#define STACK_INIT_SIZE 100 //
#define STACKINCREMENT 10 //
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;//栈底
SElemType *top;//栈顶
int stacksize;//栈当前最大容量
}SqStack;
int main()
{
void InitStack(SqStack &S);
Status Push(SqStack &S, int e);
void StackTraverse(SqStack &S);
int a, b, c;//a为原十进制数,b为需要转换的进制
SqStack S;
InitStack(S);
printf("请输入你要转换的数:");
scanf_s("%d", &a);
printf("\n");
c = a;
printf("请输入你要将%d转换成几进制:", a);
scanf_s("%d", &b);
printf("\n");
printf("您要将%d转换为%d进制!\n", a, b);
printf("\n");
while (a)
{
Push(S, a%b);
a = a/b;
}
printf("%d的%d进制为:", c, b);
StackTraverse(S);
printf("\n");
return 0;
}
void InitStack(SqStack &S)//初始化
{
S.base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
Status Push(SqStack &S, int 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;
S.top++;
return *(S.top-1);
}
void StackTraverse(SqStack &S)//遍历
{
while (S.top != S.base)
{
--S.top;
printf("%d", *S.top);
}
}