009PRI operatorPRIs[7][7] ={{HIGHER,HIGHER,LOWER,LOWER,LOWER,HIGHER,HIGHER},
010 {HIGHER,HIGHER,LOWER,LOWER,LOWER,HIGHER,HIGHER},
011 {HIGHER,HIGHER,HIGHER,HIGHER,LOWER,HIGHER,HIGHER},
012 {HIGHER,HIGHER,HIGHER,HIGHER,LOWER,HIGHER,HIGHER},
013 {LOWER,LOWER,LOWER,LOWER,LOWER,EQUAL,NO_POSSIBLE},
014 {NO_POSSIBLE,NO_POSSIBLE,NO_POSSIBLE,NO_POSSIBLE,\
015 NO_POSSIBLE,NO_POSSIBLE,NO_POSSIBLE},
016 {LOWER,LOWER,LOWER,LOWER,LOWER,NO_POSSIBLE,EQUAL}};
017
018bool ExpCalc::Calc(double x1,double x2,Operator op,double& res)
019{
020 bool flag = true;
021 switch(op)
022 {
023 case ADD_OPR:
024 res = x1 + x2;
025 break;
026 case MINUS_OPR:
027 res = x1 - x2;
028 break;
029 case MUL_OPR:
030 res = x1 * x2;
031 break;
032 case DIV_OPR:
033 if (fabs(x2) < 1e-6)
034 flag = false;
035 else
036 res = x1 / x2;
037 break;
038 default:
039 flag = false;
040 }
041 return flag;
042}
043
044bool ExpCalc::PostfixCalc(vector<double> &a,vector<Operator> &ops,double& res)
045{
046 Clear();
047 for (int i = 0;i<a.size();i++)
048 operands_stack.push(a[i]);
049 for (int i = 0;i<ops.size();i++)
050 {
051 if (operands_stack.size()>=2)
052 {
053 double x2 = operands_stack.top();
054 operands_stack.pop();
055 double x1 = operands_stack.top();
056 operands_stack.pop();
057 double r;
058 bool isOk = Calc(x1,x2,ops[i],r);
059 if (!isOk) return false;
060 operands_stack.push(r);
061 }else
062 {
063 return false;
064 }
065 }
066 res = operands_stack.top();
067 return (operands_stack.size() == 1);
068}
069void ExpCalc::Clear()
070{
071 while (!operands_stack.empty())
072 operands_stack.pop();
073 while (!operators_stack.empty())
074 operators_stack.pop();
075}
076bool ExpCalc::doWhenHigher(Operator op)
077{
078 if (operands_stack.size()<2)
079 return false;
080 double x2 = operands_stack.top();
081 operands_stack.pop();
082 double x1 = operands_stack.top();
083 operands_stack.pop();
084 double res;
085 bool isOk = Calc(x1,x2,op,res);
086 if (!isOk) return false;
087 operands_stack.push(res);
088 operators_stack.pop();
089 return true;
090}
091bool ExpCalc::doWhenLower(Operator op,Operator nxt_op)
092{
093 operators_stack.push(nxt_op);
094 return true;
095}
096bool ExpCalc::doWhenEqual()
097{
098 if (operators_stack.empty())
099 return false;
100 operators_stack.pop();
101 return true;
102}
103