设一个判断运算符优先级的函数 char Precede(char a, char b);
根据运算符的不同,自然有不同操作 int operate(int a, char theta, int b);
不同运算符间的如下优先顺序:
实现代码如下:
# include<iostream> # include<stack> using namespace std; int operate(int a, char theta, int b); char Precede(char a, char b); int main() { stack<char> operators;// 运算符栈 stack<int> operands;// 操作数栈 char num[15]; // 用于存储表达式中连续输入的多位数字 int result_flag = 1; operators.push('#'); cout << "请输入表达式,并以”#“结尾\n"; char ch ; cin >> ch; while (ch != '#' || operators.top()!= '#') { int i = 0, a, b, byte_flag = 0; char theta; if (ch<'0' || ch>'9') { char comp = Precede(operators.top(), ch); switch (comp) { case '>': theta = operators.top(); cout << "开始执行" << theta << "运算:\n"; cout << theta << "出操作符栈\n"; operators.pop(); b = operands.top(); cout << b << "出操作数栈\n"; operands.pop(); a = operands.top(); cout << a << "出操作数栈\n"; operands.pop(); cout << a << theta << b << "=" << operate(a, theta, b)<<endl; cout << operate(a, theta, b) << "进操作数栈\n"; operands.push(operate(a, theta, b)); break; case '=': // 左括号判断到右括号,将右括号出栈 cout << operators.top() << "出栈" << endl; operators.pop(); cin >> ch; break; case '<': cout << ch << "进操作符栈\n"; operators.push(ch); cin >> ch; break; case '!': cout << "输入的表达式存在语法错误\n"; result_flag = 0; cin >> ch; break; } continue; } while (ch >= '0'&&ch <= '9') { byte_flag = 1; num[i++] = ch; cin>>ch; } if (byte_flag) { num[i] = '\0'; cout << atoi(num) << "进操作数栈\n"; operands.push(atoi(num)); } } if (result_flag) cout << "表达式最终结果为:" << operands.top() << endl; return 0; } int operate(int a, char theta, int b) // 执行 a operater b { if (theta == '+') return a + b; else if (theta == '-') return a - b; else if (theta == '*') return a*b; else if (theta == '/') return a / b; } char Precede(char a, char b)//比较两个运算符的优先级,a运算符在b左边 { if (a == '+' || a == '-') { if (b == '+' || b == '-' || b == ')' || b == '#') return '>'; else return '<'; } else if (a == '*' || a == '/') { if (b == '(') return '<'; else return '>'; } else if (a == '(') { if (b == '+' || b == '-' || b == '*' || b == '/' || b == '(') return '<'; else if (b == ')') return '='; else { return '!'; } } else if (a == ')') { if (b == '+' || b == '-' || b == '*' || b == '/' || b == ')' || b == '#') return '>'; else if (b == '(') { return '!'; } } else if (a == '#') { if (b == ')') { return '!'; } else if (b == '#') return '='; else return '<'; } }