十進制數N轉換成其他d進制數的轉換是計算機實現計算的基本問題,解決方法很多,其中一個簡單算法基於如下原理:N=(N div d)*d +N mod d ,主要涉及到進棧和出棧。
算法描述://十進制轉換成其他進制
void coversion ()
{
int N,e,d;//十進制N轉換成d進制數
InitStack(&S);//構造空棧
scanf(“%d”,&N);
while(N)
{
e=N%d;
Push(S,e);
N=N/d;
}
whlie(!StackEmpty(S))
{
Pop(S,e);
printf(“%d”,e);
}
}
——————C代碼實現————————在VC++ 6.0編譯通過,運行成功——————————————
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define STACK_INNT_SIZE 100//存儲空間初始分配量
#define STACKINCREMENT 10//存儲空間分配增量
typedef struct
{
int * base;//構造前或者銷燬後,base=NULL.
int * top;//棧頂指針
int stacksize;
}SqStack;
//構造空棧
void InitStack(SqStack &S)
{
S.base=(int *)malloc(STACK_INNT_SIZE * sizeof(int));
if(!S.base)
{
printf("malloc failed.\n");
exit(0);
}
S.top=S.base;
S.stacksize=STACK_INNT_SIZE;
}
void Push(SqStack &S,int e)//進棧
{
if(S.top-S.base>=S.stacksize)
{
S.base=(int *)realloc(S.base,(S.stacksize + STACKINCREMENT)*sizeof(int));
if(!S.base)
{
printf("malloc failed.\n");
exit(0);
}
S.top=S.base + S.stacksize;
S.stacksize +=STACKINCREMENT;
}
*S.top++=e;
}
void Pop(SqStack &S,int &e)//出棧
{
if(S.top==S.base)
{
printf("Stack Empty!\n");
exit(0);
}
e=*--S.top;
}
void main()
{
int N,e,m;
SqStack S;
InitStack(S);
printf("轉換成幾進制:\n");
scanf("%d",&m);
printf("輸入十進制:\n");
scanf("%d",&N);
while(N)
{
e=N%m;
Push(S,e);
N=N/m;
}
while(S.top != S.base)
{
Pop(S,e);
printf("%d",e);
}
printf("\n");
//return 0;
}