利用栈对表达式求值
根据运算符的各运算符的优先顺序,确定入栈操作
- if(compare(s2.top(),s[i])==-1)栈内的优先级小,栈外的运算符入栈
- if(compare(s2.top(),s[i])==0)栈内的优先级与栈外的优先级相同,栈内运算符出栈
- if(compare(s2.top(),s[i]==1)栈内优先级大,进行运算
判断优先级
以a为栈头,以b为栈外符号
- a=='!'
- a=='&'
- a=='|'
- a=='-
- a=='='
- a=='(';
代码如图所示 (具体优先级)
if (a == '!'){if (b == '(')return -1;else if (b == '!')return 0;else return 1;}else if (a == '&'){if (b == '(' || b == '!')return -1;else return 1;}else if (a == '|'){if (b=='&'|| b == '(' || b == '!')return -1;else return 1;}else if (a == '-'){if (b=='&'|| b == '(' || b == '|' || b == '!')return -1;else return 1;}else if (a == '='){if (b == '=' || b == ')')return 1;else return -1;}else if (a == '('){if (b == ')')return 0;else return -1;}
表达式的运算(离散数学知识):
int value(int a, char c, int b)
{if (c == '&')return a * b;if (c == '|'){if (a == 0 && b == 0)return 0;else return 1;}if (c == '-')if (a == 1 && b == 0)return 0;else return 1;if (c == '='){if (a == b)return 1;else return 0;}
}