
/**//***************************

表达式模板

****************************/
#include<stack>
#include<string>
#include<iostream>
using namespace std;

int signMap[7][7]=


{

{'>','>','<','<','<','>','>'}, // +

{'>','>','<','<','<','>','>'}, // -

{'>','>','>','>','<','>','>'}, // *

{'>','>','>','>','<','>','>'}, // /

{'<','<','<','<','<','=','#'}, // (

{'>','>','>','>','#','>','>'}, // )

{'<','<','<','<','<','#','='}, // #
};


char element[7]=
{'+','-','*','/','(',')','#'};

char Precede(char oper1,char oper2)


{
int i,j;
for(i=0;i<7;i++)

{
if(element[i]==oper1) break;
}
for(j=0;j<7;j++)

{
if(element[j]==oper2) break;
}
return signMap[i][j];
}

int Operate(int a,char oper,int b)


{
switch(oper)

{
case '+':
return a+b;
break;
case '-':
return a-b;
break;
case '*':
return a*b;
break;
case '/':
return a/b;
break;
default:
cerr<<"Operate Error"<<endl;
return 0;
}
}

int Calculate(string &str)


{
int a,b,t2;
char oper;
stack<int> opnd;
stack<char> optr;
optr.push('#');
str=str+'#';
int index=0;
while(optr.top()!='#'||str[index]!='#')

{
while(str[index]==' ') index++;
if(!(str[index]=='+'||str[index]=='-'||
str[index]=='*'||str[index]=='('||str[index]==')'||str[index]=='#'))

{
opnd.push(str[index++]-'0');
}
else

{
char t=Precede(optr.top(),str[index]);
switch(t)

{
case '<':
optr.push(str[index++]);
break;
case '=':
optr.pop();
index++;
break;
case '>':
oper=optr.top();
optr.pop();
a=opnd.top();
opnd.pop();
b=opnd.top();
opnd.pop();
t2=Operate(b,oper,a);
opnd.push(t2);
break;
default:
cerr<<"Operate Error"<<endl;
return 0;
}
}
}
return opnd.top();
}
posted on 2009-04-17 21:00
姚冰 阅读(277)
评论(0) 编辑 收藏 引用