11.28
include
include
include
include
include
include
using namespace std;
// 检查运算符优先级:、/ 优先级为2,+、- 为1,括号为0
int getPriority(char op) {
if (op == '' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0; // 括号
}
// 合法性检查:括号匹配 + 操作符连续性
bool isValid(const string& expr) {
int bracket = 0;
bool prevIsOp = true; // 初始时前一个是“虚拟运算符”(不能以运算符开头)
for (char c : expr) {
if (c == '(') {
bracket++;
prevIsOp = true; // 左括号后可以跟运算符(如(+2)不合法,但这里先标记)
} else if (c == ')') {
bracket--;
if (bracket < 0) return false; // 右括号比左括号多
prevIsOp = false; // 右括号后不能跟数字
} else if (isdigit(c)) {
prevIsOp = false;
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
if (prevIsOp) return false; // 连续运算符
prevIsOp = true;
}
}
if (bracket != 0) return false; // 括号不匹配
if (prevIsOp) return false; // 表达式以运算符结尾
return true;
}
// 中缀转后缀
string infixToPostfix(const string& expr) {
stack
string postfix;
for (char c : expr) {
if (isdigit(c)) {
postfix += c;
} else if (c == '(') {
opStack.push(c);
} else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix += opStack.top();
opStack.pop();
}
opStack.pop(); // 弹出左括号
} else { // 运算符
while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(c)) {
postfix += opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
// 弹出剩余运算符
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
// 后缀求值
int calculatePostfix(const string& postfix) {
stack
for (char c : postfix) {
if (isdigit(c)) {
numStack.push(c - '0');
} else {
int b = numStack.top(); numStack.pop();
int a = numStack.top(); numStack.pop();
int res;
switch (c) {
case '+': res = a + b; break;
case '-': res = a - b; break;
case '*': res = a * b; break;
case '/': res = a / b; break; // 题目中是整数运算
}
numStack.push(res);
}
}
return numStack.top();
}
int main() {
string input;
getline(cin, input);
// 过滤空格
string expr;
for (char c : input) {
if (c != ' ') expr += c;
}
// 合法性检查
if (!isValid(expr)) {
if (count(expr.begin(), expr.end(), '(') != count(expr.begin(), expr.end(), ')')) {
cout << "ERROR:缺少括号" << endl;
} else {
cout << "ERROR:表达式缺操作数" << endl;
}
return 0;
}
// 中缀转后缀
string postfix = infixToPostfix(expr);
// 后缀求值
int result = calculatePostfix(postfix);
// 输出
cout << "后缀表达式: " << postfix << endl;
cout << "计算结果: " << result << endl;
return 0;
}

浙公网安备 33010602011771号