注意本代码只是简单实现了运算功能,而且字符串中的数字只能一位,除法运算结果最好不要有小数,因为没有准备小数相关功能,强行运算会中断程序或失去小数精确度。
#include<iostream>
#include<stack>
#include<map>
using namespace std;
//定义一个运算类
class run {
public:
//临时保存数字
stack<int>number;
//临时保存运算符
stack<char>op;
//使用哈希表直接查询运算符号优先级
map<char, int>map;
//构造函数直接定义运算符优先级
run() {
map['+'] = map['-'] = 1;
map['*'] = map['/'] = 2;
map['('] = 0;
map[')'] = 0;
}
//运算两个值
int x(int a, int b, char op) {
if (op == '+') {
return a + b;
}
else if (op == '-') {
return a - b;
}
else if (op == '*') {
return a * b;
}
else {
return a / b;
}
}
//处理表达式
int running(string expression) {
//高级for循环,每次拿出一个字符
for (auto it : expression) {
//数字
if (it >= '0' && it <= '9') {
number.push(it-'0');
}
//运算符
else {
if (op.empty()) {
op.push(it);
}
else {
if (it == '(') {
op.push(it);
}
else {
while (!op.empty()&&op.top() != '(' && map[op.top()] > map[it]) {
int a = number.top(); number.pop();
int b = number.top(); number.pop();
char c = op.top(); op.pop();
number.push(x(b, a, c));
}
op.push(it);
}
}
}
}
//当数字栈不为空
while (number.size()>1) {
int a = number.top(); number.pop();
int b = number.top(); number.pop();
char c;
while ((c = op.top()) == '(' || c == ')') {
op.pop();
}
number.push(x(b, a, c));
}
return number.top();
}
};
int main() {
cout << run().running("((4*3+5)*(2+4))*(5+5)") << endl;
}