You are on page 1of 2

#include <iostream>

using namespace std;


#include<stack>
int level(char x) {
if (x == '+' || x == '-')return 1;
if (x == '*' || x == '/')return 2;
if (x <= '9' && x >= '0')return 0;
if (x == '(')return -1;
}
int cal(int a, int b, char x) {
if (x == '+')return a + b;
if (x == '-')return a - b;
if (x == '*')return a * b;
if (x == '/')return a / b;

}
void main()
{
stack<int>num;
stack<char>s;
cout << "输入规则:表达式前后加 # ,如 #3+(2-6)/4# " << endl;
cout << "请输入表达式:";
string x;
cin >> x;
if (x[0] != '#') {
cout << "格式错误,开头不为 # " << endl;
return;
}
if (x[x.size()] != '#') {
cout << "格式错误,结尾不为 # " << endl;
return;
}
for (int i = 1;; i++) {//零级
if (x[i] >= '0' && x[i] <= '9') {//一级,数字
int n = x[i]-'0';
i++;
while (x[i] >= '0' && x[i] <= '9') {
n = n * 10 + x[i] - '0';
i++;
}
i--;
num.push(n);
}
else {//一级,符号
if ((x[i] != ')' && s.empty())||x[i]=='(') { //二级,运算符号,空栈或
左括号
s.push(x[i]);
continue;
}
if (!s.empty() && x[i] != ')'&&x[i]!='('&&x[i]!='#') {//二级,符号
比较,非空,不考虑括号
if (level(x[i]) <= level(s.top())) {//三级,直接计算,符号再入

int m = num.top();
num.pop();
int n = num.top();
num.pop();
num.push(cal(n,m,s.top()));
s.pop();
s.push(x[i]);
continue;
}
if (level(x[i]) > level(s.top())) {//三级,符号直接入栈
s.push(x[i]);
continue;
}
}
if (x[i] == ')') {//二级,括号
while (s.top() != '(') {
int a = num.top();
num.pop();
int b = num.top();
num.pop();
num.push(cal(b, a, s.top()));
s.pop();
}
s.pop();
continue;
}
if (x[i] == '#') {//二级,结束
while (!s.empty()) {
int a = num.top();
num.pop();
int b = num.top();
num.pop();
num.push(cal(b, a, s.top()));
s.pop();
}
break;
}
}
}
cout << "结果为:" << num.top();
}

You might also like