利用栈实现进制转换1,常用进制转换成十进制

根据栈的特性,FILO,很方便的就可以实现进制转换。 
关于栈的一系列操作,在此不再做任何赘述。我这里只是介绍一下压栈(psuhStack),和弹栈(popStack): 
1.压栈:就是把元素一个一个的压入栈中。例如:八进制的数值 12345670 进栈的时候,1先进,2再进……..0最后才进。 
2.弹栈:就在把栈中的元素一个一个的取出来。例如:栈中存储了八进制数值12345670,0先出,7再出,…….1最后出。

了解了基本的压栈弹栈后,那么现在开始想想如何进行进制转换?常用的就是挨个值进行乘radix的i次幂(i=0,1,2,3,4,5,6,……)。

 


代码如下:

#include <stdio.h>
# include <stdlib.h>
#include <math.h>
#define LEN sizeof(struct Stack)
#define StackSize 100
#define StackSizeIncreament 10
extern int *initStack(Stack *stack);
extern int pushStack(Stack *stack,ElemType ch);
extern int popStack(Stack *stack,ElemType *e);
extern double fun(int radix,Stack *stack);
extern double demo(int radix);
typedef char ElemType; 

typedef struct Stack 

ElemType *top,*base; 
int length; 
}Stack;

int main() 

demo(2); 
demo(3); 
demo(4); 
demo(5); 
demo(6); 
demo(7); 
demo(8); 
demo(9); 
demo(10); 
return 0; 
}

int *initStack(Stack *stack) 
//初始化栈,成功返回1 

stack->base = (ElemType *)malloc(LEN); 
if(!stack->base)return 0; 
stack->top = stack->base; 
stack->length = StackSize; 
return 1; 
}

int pushStack(Stack *stack,ElemType ch) 
//压栈, 

if(stack->top - stack->base >= stack->length) 

stack->base = (ElemType *)realloc(stack->base,stack->length+StackSizeIncreament); 
if(!stack->base)return 0; 
stack->top += stack->length; 
stack->length += StackSizeIncreament; 

*(stack->top ++) = ch; 
return 1; 
}


int popStack(Stack *stack,ElemType *e) 
//弹栈 

if(stack->base == stack->top) 

//printf(“\nstack is null\n”); 
return 0; 

e = –stack->top; 
return 1; 
}

//注意:由于pow函数的返回值类型是double,在强制类型转换的时候,会造成数值的不准确。
//所有fun函数也用double型。

double fun(int radix,Stack *stack) 
//进行进制转换,返回转换后的十进制数。 

double num=0; 
int i=0; 
char ch; 
while(popStack(stack,&ch)) 

if((ch-=’0’)>=radix) //判断输入的数据是否是该进制数。

printf(“\n\binput Error!!\n”); 
return -1; 

num+=(ch * pow(radix,i++)); 

return num; 
}

int demo(int radix) 
//测试用例 

Stack stack; 
char ch; 
if(!initStack(&stack)) 
return 0; 
printf(“Please Enter %d radix num:”,radix); 
while((ch=getchar())!=’\n’) 

if( !pushStack(&stack,ch) ) 
break; 

printf(“after convert:%0.0f\n\n”,fun(radix,&stack)); 
}

本人原创,欢迎转载,如有雷同,不胜荣幸。 
如有错误,欢迎一起讨论。 
QQ:1586487767

posted @ 2015-11-14 15:53  方家小白  阅读(33)  评论(0编辑  收藏  举报