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语言描述


3、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;       

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值