calculator.h
上传用户:sycq158
上传日期:2008-10-22
资源大小:15361k
文件大小:3k
- ///////本程序完成简易的calculator,为用户输入做准备!
- #define MAX_STACK_SIZE 50
- #define MAX_EXPR_SIZE 50
- enum precedence{lparen,rparen,plus,minus,times,divide,eos,operand};
- static int isp[7]={0,19,12,12,13,13,0};
- static int icp[7]={20,19,12,12,13,13,0};
- //expr 是中缀表达式以等于号结束!
- char expr[MAX_EXPR_SIZE];
- //string 是后缀表达式
- char string[MAX_EXPR_SIZE];
- //length 是string 的长度
- precedence pstack[MAX_STACK_SIZE];
- float stack[MAX_STACK_SIZE];
- short poke[4];
- ///////////////////////////////////////
- void add(int &top,float p)
- {
- if(top<49)
- stack[++top]=p;
- else
- exit(-1);
- }
- float del(int &top)
- {
- if(top==-1)
- exit(0);
- else
- return stack[top--];
- }
- //////////////////////////////////////////////
- void add(int &top,precedence poke)
- {
- if(top<49)
- pstack[++top]=poke;
- else
- exit(-1);
- }
- precedence delt(int &top)
- {
- if(top==-1)
- exit(-1);
- else
- return pstack[top--];
- }
- char print_token(precedence token)
- {
- switch(token)
- {
- case lparen:return '(';
- case rparen:return ')';
- case plus: return '+';
- case minus: return '-';
- case times: return '*';
- case divide:return '/';
- case eos: return '=';
- default :return NULL ;
- }
-
- }
- precedence get_token(char&symbol,int &n)
- {
-
- symbol=expr[n++];
- switch(symbol)
- {
- case '(':return lparen;
- case ')':return rparen;
- case '+':return plus;
- case '-':return minus;
- case '*':return times;
- case '/':return divide;
- case '=':return eos;
- default :return operand;
- }
- }
- void postfix( )
- {
- char symbol;
- precedence token;
- int n=0;
- pstack[0]=eos;
- int top=0;
- int length=0;
- for(token=get_token(symbol,n);token!=eos;token=get_token(symbol,n))
- {
- if(token==operand)
- string[length++]=symbol;
-
- else if(token==rparen)
- {
- while(pstack[top]!=lparen)
- {
- string[length++]=print_token(delt(top));
- }
- delt(top);
- }
-
- else{
- while(isp[pstack[top]]>=icp[token])
- string[length++]=print_token(delt(top));
- add(top,token);
- }
- }
- while((int)(token=delt(top))!=(int)eos)
- {
- string[length++]=print_token(token);
- }
- string[length++]='=';
- string[length]=NULL;
- }
- precedence gettoken(char&symbol,int &n)
- {
-
- symbol=string[n++];
- switch(symbol)
- {
- case '+':return plus;
- case '-':return minus;
- case '*':return times;
- case '/':return divide;
- case '=':return eos;
- default :return operand;
- }
- }
- float eval()
- {
- precedence token;
- char symbol;
- float op1;
- float op2;
- int n=0;
- int top=-1;
- token=gettoken(symbol,n);//应用
- while(token!=eos)
- {
- if(token==operand)
- add(top,poke[(int)symbol-48]);//应用
-
- else{
- op2=del(top);
- op1=del(top);
- switch(token)
- {
- case plus:add(top,op1+op2);break;
- case minus: add(top,op1-op2);break;
- case times: add(top,op1*op2);break;
- case divide: add(top,op1/op2);break;
- }
- }
- token=gettoken(symbol,n);
- }
- return del(top);
- }