将十进制数转化为其他进制的数,用到栈的简单操作。
c代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef int SelemType;
typedef struct
{
SelemType data[MAXSIZE];
int top;
}SqStack;
/// 初始化一个空栈
void InitStack(SqStack *s)
{
s->top = -1;
}
///判断栈是否为空
bool StackEmpty(SqStack s)
{
if(s.top == -1)
return true;
else
return false;
}
///插入e为栈顶新元素
Status Push(SqStack *s, SelemType e)
{
if(s->top == MAXSIZE-1) ///栈满
return OVERFLOW;
s->top++; ///栈顶指针加一
s->data[s->top] = e; ///新元素赋值到栈顶
return OK;
}
///删除并得到栈顶元素,用e返回
Status Pop(SqStack *s,SelemType *e)
{
if(StackEmpty(*s))
return ERROR;
*e = s->data[s->top];
s->top--;
return OK;
}
//十进制整数转换为其他进制数
void Transform(int num,int mod)//实现进制转换
{
int h;
SqStack Stack;
InitStack(&Stack);
printf("转化结果为:");
if(num<0)
num = (-1)*num;
if(num==0)
printf("0\n");
else
{
while(num!=0)
{
h = num%mod; //取余
Push(&Stack, h);
num = num/mod; //取整
}
while(!StackEmpty(Stack))
{
Pop(&Stack, &h);
if( h<10 )
printf("%d",h);
else
printf("%c",(char)(h-10+'a'));
}
printf("\n");
}
}
int main()
{
int n, r;
printf("请输入要转化的十进制数n:");
scanf("%d",&n);
printf("请输入要转化的进制R:");
scanf("%d",&r);
Transform(n, r);
return 0;
}