这里是11.19随笔。
题目留档:使用键盘输入数学表达式(含数字,四种运算符+、-、、/和小括号,其中运算数都是一位数(0~9)),将数学表达式转化成后缀表达式输出,利用后缀表达式求表达式的值并输出。
输入格式:
输入正确的表达式(可以有空格)后回车,得到后缀表达式和结果。输入括号缺失的表达式,输出"ERROR:缺少括号"。输入两个除括号外运算符连续的表达式,输出"ERROR:表达式缺操作数"。
输出格式:
请在这里描述输出格式。例如:对每一组输入,在一行中输出A+B的值。
代码:
include
include
include
include
include
// 比较运算符优先级
int precedence(char op) {
if (op == '(') return 0;
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return -1;
}
// 中缀表达式转后缀表达式
std::string infixToPostfix(const std::string& infix) {
std::stack
std::string postfix;
std::istringstream iss(infix);
char ch;
char prev = ' ';
while (iss >> ch) {
if (std::isdigit(ch)) {
postfix += ch;
prev = ch;
} else if (ch == '(') {
operators.push(ch);
prev = ch;
} else if (ch == ')') {
while (!operators.empty() && operators.top()!= '(') {
postfix += operators.top();
operators.pop();
}
if (operators.empty()) {
return "ERROR:缺少括号";
}
operators.pop();
prev = ch;
} else {
if ((prev == '+' || prev == '-' || prev == '' || prev == '/') && (ch == '+' || ch == '-' || ch == '' || ch == '/')) {
return "ERROR:表达式缺操作数";
}
while (!operators.empty() && precedence(operators.top()) >= precedence(ch)) {
postfix += operators.top();
operators.pop();
}
operators.push(ch);
prev = ch;
}
}
while (!operators.empty()) {
postfix += operators.top();
operators.pop();
}
return postfix;
}
// 计算后缀表达式的值
int evaluatePostfix(const std::string& postfix) {
std::stack
for (char ch : postfix) {
if (std::isdigit(ch)) {
operands.push(ch - '0');
} else {
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
switch (ch) {
case '+':
operands.push(operand1 + operand2);
break;
case '-':
operands.push(operand1 - operand2);
break;
case '*':
operands.push(operand1 * operand2);
break;
case '/':
operands.push(operand1 / operand2);
break;
}
}
}
return operands.top();
}
int main() {
std::string infix;
std::getline(std::cin, infix);
std::string postfix = infixToPostfix(infix);
std::cout << postfix << std::endl;
if (postfix.find("ERROR") == std::string::npos) {
std::cout << evaluatePostfix(postfix) << std::endl;
} else {
std::cout << postfix << std::endl;
}
return 0;
}