栈的应用举例之进制转换

来源:互联网 发布:都有什么数据库 编辑:程序博客网 时间:2024/06/05 00:51

十进制数N和其他d进制数的转换时计算机实现甲酸的基本问题,其解决方法很多,其中一个简单算法基于下列原理:

N=(N div d)×d+N mod d (其中,div为整除运算,mod为求余运算)

例如:(1348)10=(2504)8,其运算过程如下:


代码实现:

#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0#define OVERFLOW -2#define STACK_INT_SIZE 100#define STACKINCREMENT 10
typedef struct{    int *base;    int *top;    int stacksize;}SqStack;
//InitStack

int InitStack(SqStack &S){    S.base=(int *)malloc(STACK_INT_SIZE*sizeof(int));    if(!S.base)        exit(OVERFLOW);    S.top=S.base;    S.stacksize=STACK_INT_SIZE;    return OK;}
//Push

int 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)            exit(OVERFLOW);        S.top=S.base+S.stacksize;        S.stacksize+=STACKINCREMENT;    }    *S.top++=e;    return OK;}

//StackEmpty

int StackEmpty(SqStack S) {   if(S.top==S.base)     return TRUE;   else     return FALSE; }

//StackEmpty

int StackEmpty(SqStack S) {   if(S.top==S.base)     return TRUE;   else     return FALSE; }

//Pop

int Pop(SqStack &S,int &e){    if(S.top==S.base)        return ERROR;    e=*--S.top;    return OK;}

//conversion

void conversion(){    SqStack S;    InitStack(S);    int N;    printf("请输入一个十进制数N:");    scanf("%d",&N);    int d;    printf("请输入进制位d:");    scanf("%d",&d);    while(N){        Push(S,N%d);        N=N/d;    }    printf("十进制数N转换为d进制数:");    while(!StackEmpty(S)){        int e;        Pop(S,e);        printf("%d",e);    }}

//main

int main(){    conversion();}




0 0
原创粉丝点击