5、进制转换(整数)
一、用一般函数实现
#include "stdio.h"
void fun(int m,int k)
{
int i,a[20];
for(i=0;m;i++)
{
a[i]=m%k;
m/=k;
}//for
for(;i;i--)
printf("%d",a[i-1]);
}
int main()
{
int b,n;
printf("Please input: ");
scanf("%d%d",&n,&b);
fun(n,b);
}
二、用栈实现
1、其实,进行转换是一个典型的栈的应用例子,下在我们以8<->10进制转换为例。
2、C语言描述
#include "stdio.h"
#include "stdlib.h"
#define STACK_INIT_SIZE 1000
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
typedef int Elemtype;
typedef int Status;
typedef struct Stack
{
Elemtype*base;
Elemtype*top;
intstacksize;
}SqStack;
Status InitStack(SqStack &S)
{
S.base=S.top=(Elemtype*)malloc(STACK_INIT_SIZE*sizeof(SqStack));
if(!S.base) exit(-1);
S.stacksize=S.stacksize;
return OK;
}//InitStack
Status Push(SqStack &S,int e)
{
if(S.top-S.base>=STACK_INIT_SIZE)
{
S.base=(Elemtype*)realloc(S.base,(STACK_INIT_SIZE+STACKINCREMENT)*sizeof(SqStack));
if(!S.base)exit(-1);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}//if
*S.top=e;
S.top++;
return OK;
}//Push
Status Pop(SqStack &S,int &e)
{
if(S.top==S.base) return ERROR;
S.top--;
e=*S.top;
return OK;
}//Pop
Status StackEmpty(SqStack S)
{
if(S.top==S.base) return 1;
else return 0;
}//StackEmpty
void conversion(SqStack &S,int N,int n)
{
while(N)
{
Push(S,N%n);
N=N/n;
}//while
while(!StackEmpty(S))
{
inte;
Pop(S,e);
printf("%d",e);
}//while
}//conversion
Status Destroystack(SqStack &S)
{
free(S.base);
free(S.top);
S.stacksize=0;
return OK;
}
int main()
{
SqStack S;
InitStack(S);
printf("Input m and n(m is in decimal,concert itin n system)\n");
int m,n;
scanf("%d",&m);
scanf("%d",&n);
conversion(S,m,n);
Destroystack(S);
return 1;
}