以下是使用C++实现将中缀表达式转换为后缀表达式的代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getPriority(char op) {
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
return 0;
}
string infixToPostfix(string expression) {
stack<char> operators;
string postfix = "";
for (int i = 0; i < expression.length(); i++) {
char ch = expression[i];
// 忽略空格
if (ch == ' ')
continue;
// 操作数直接加入后缀表达式中
if (isalnum(ch))
postfix += ch;
// 左括号直接入栈
else if (ch == '(')
operators.push(ch);
// 右括号将栈内运算符弹出并加入到后缀表达式中,直到遇到左括号
else if (ch == ')') {
while (!operators.empty() && operators.top() != '(') {
postfix += operators.top();
operators.pop();
}
// 弹出左括号
operators.pop();
}
// 运算符处理逻辑
else {
while (!operators.empty() && getPriority(ch) <= getPriority(operators.top())) {
postfix += operators.top();
operators.pop();
}
operators.push(ch);
}
}
// 将栈内剩余运算符弹出并加入到后缀表达式中
while (!operators.empty()) {
postfix += operators.top();
operators.pop();
}
return postfix;
}
float evaluatePostfix(string postfix) {
stack<float> operands;
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix[i];
// 操作数入栈
if (isdigit(ch)) {
operands.push(ch - '0');
}
// 运算符处理逻辑
else {
float operand2 = operands.top();
operands.pop();
float 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;
default:
cout << "无效的运算符" << endl;
return 0.0f;
}
}
}
// 返回最终结果
return operands.top();
}
int main() {
string expression;
getline(cin, expression, '#');
string postfix = infixToPostfix(expression);
cout << "转换的后缀表达式为:" << postfix << endl;
float result = evaluatePostfix(postfix);
cout << "计算结果为:" << result << endl;
return 0;
}
注意,上述代码假定输入的中缀表达式是有效的,并且只包含加法、减法、乘法和除法运算符。对于其他类型的运算符或者更复杂的表达式,可能需要进行适当的修改。
内容由零声教学AI助手提供,问题来源于学员提问