魔装少男的博客

我可爱又美丽却能唤来死亡
虽然我可爱又迷人,但我能招来死亡

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

#define OK 1 //通过

#define ERROR 0 //错误

#define OVERFLOW -2 //堆栈溢出

#define MAXSIZE 50 //容量

typedef int Status; //函数类型,其值为状态码

typedef int ElemType; //抽象数据类型

  //顺序结构储存

typedef struct

{

ElemType* base;

ElemType* top;

int stacksize;

}SqStack;

typedef enum

{

f, t

}Bool;

//初始化

Status initStack(SqStack* S)

{

S->base = new ElemType[MAXSIZE];

if (!S->base)

{

exit(OVERFLOW);

}

S->top = S->base;

S->stacksize = MAXSIZE;

return OK;

}

//判空

Bool isEmpty(SqStack* S)

{

return S->base == S->top ? t : f;

}

//长度

int getLength(SqStack* S)

{

return S->top - S->base;

}

//入栈

Status pushElem(SqStack* S, ElemType e)

{

if (getLength(S) == S->stacksize)return ERROR;

*(S->top) = e;

S->top++;

return OK;

}

//出栈

ElemType popElem(SqStack* S)

{

if (isEmpty(S))return NULL;

S->top--;

return *(S->top);

}

//取栈顶

ElemType getTop(SqStack* S)

{

if (!isEmpty(S))return *(S->top - 1);

return NULL;

}

//数字转字符

char sTOc(int index)

{

char* arr = "0123456789ABCDEFGHIJLMNOPQRTUVWXYZ";

return index > 36&&index<0 ? '#' : arr[index];

}

//进制转换

Status conversion()

{

int  k = 0;

double n = 0;

while (!(n > 0))

{

printf("请输入需要转换的数(大于0,可以有小数) ");

scanf_s("%lf", &n);

}

while (!(k >= 2&&k<37))

{

printf("请输入进制整数(例如 2 大于1 小于37");

scanf_s("%d", &k);

}

SqStack *SX1 = NULL;

SqStack *SX2=NULL;//存放小数部分,可用队列替换

SqStack* SI = new SqStack;//存放整数部分

initStack(SI);

int nn = floor(n);

//整数部分

while (nn)

{

pushElem(SI, nn%k);

nn= nn/ k;

}

//小数部分

if (0 !=n - floor(n))

{

SX1 = new SqStack;

initStack(SX1);

SX2 = new SqStack;

initStack(SX2);

int i = 0;

while (0!=n - floor(n) &&i<10)

{

n = (n - floor(n))*k;

pushElem(SX1, (int)floor(n));

++i;

}

//小数部分是顺序的

while (!isEmpty(SX1))

{

pushElem(SX2,popElem(SX1));

}

}

if (isEmpty(SI))//整数部分为0时,保证可用输出0

{

printf("%c", sTOc(0));

}

while (!isEmpty(SI))//整数部分

{

printf("%c",sTOc(popElem(SI)));

}

if (NULL!=SX2)//小数部分

{

printf("%s", ".");

while (!isEmpty(SX2))

{

printf("%c", sTOc(popElem(SX2)));

}

}

delete SX2;

SX2 = NULL;

delete SX1;

SX1 = NULL;

delete SI;

SI = NULL;

return OK;

}

int main(void)

{

conversion();//演示正整数 进制低于11

printf("\n");

conversion();//演示纯小数 进制低于11

printf("\n");

conversion();//演示小数 进制低于11

printf("\n");

conversion();//演示正整数 进制高于10

printf("\n");

conversion();//演示纯小数 进制高于10

printf("\n");

conversion();//演示小数 进制高于10

printf("\n");

conversion();//演示小数 进制远高于10

printf("\n");

system("pause");

return 0;

}