You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

141 lines
3.9 KiB

// https://blog.csdn.net/amf12345/article/details/96868717
#include<bits/stdc++.h>
using namespace std;
//四则运算的类
class fourArithmeticOperation {
public:
//四则运算的字符串
string s;
//数字栈
stack<int> val;
//操作符栈
stack<char> symbol;
//构建函数
fourArithmeticOperation() {
symbol.push('#');
}
//表达式计算的过程
int process() {
int i = 0, num;
while (symbol.top() != '#' || i < s.size()) {
//发现了数字
if (s[i] >= '0' && s[i] <= '9') {
//为操作数
num = 0;
//根据字符串转为数字的方法
while (s[i] >= '0' && s[i] <= '9') {//一直向后找是数字的
num *= 10;
num += s[i] - '0';
++i;
}
//数字入栈
val.push(num);
cout << num << "入栈val" << endl;
} else {
switch (cmp(symbol.top(), s[i])) {
case '<':
symbol.push(s[i]);
//调试信息
cout << s[i] << "入栈symbol" << endl;
++i;
break;
case '=': //用于前后等号对掉
//调试信息
cout << symbol.top() << "出栈symbol" << endl;
symbol.pop();
++i;
break;
case '>':
int a = val.top();
val.pop();
int b = val.top();
//出栈
cout << b << "出栈val" << endl;
val.pop();
val.push(cal(b, a, symbol.top()));
//调试信息
cout << a << symbol.top() << b << "=" << val.top() << endl;
cout << val.top() << "入栈val" << endl;
//出栈
cout << symbol.top() << "出栈symbol" << endl;
symbol.pop();
break;
}
}
}
int res = val.top();
val.pop();
return res;
}
//操作符之间的优先级的比较
char cmp(char a, char b) {
//右括号不会进栈,不必写右括号的优先级
//遇到右括号就弹出左括号
if (a == '#') {
if (b == '#') {
return '=';
} else {
return '<';
}
}
if (a == '+' || a == '-') {
if (b == '*' || b == '/' || b == '(') {
return '<';
} else {
return '>';
}
}
if (a == '*' || a == '/') {
if (b == '(') {
return '<';
} else {
return '>';
}
}
if (a == '(') {
if (b == ')') {
return '=';
} else {
return '<';
}
}
}
//返回计算结果
int cal(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
}
};
int main() {
fourArithmeticOperation s1;
//测试用例: (1+2)*(4-3)
s1.s = "(1+2)*(4-3)";
cout << s1.process() << endl;
//换行
cout << endl;
//测试用例: (4-2)/2*3-4;
s1.s = "(4-2)/2*3-4";
cout << s1.process() << endl;
return 0;
}