以下是修改后的代码,不会输出#:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 判断字符是否为运算符
bool isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
// 获取运算符的优先级
int getPriority(char op) {
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
return 0;
}
// 中缀表达式转后缀表达式
string infixToPostfix(string infix) {
stack<char> operators; // 运算符栈
string postfix = ""; // 后缀表达式
for (char ch : infix) {
if (ch != '#') { // 排除 #
if (ch == '(') {
operators.push(ch);
}
else if (ch == ')') {
while (!operators.empty() && operators.top() != '(') {
postfix += operators.top();
operators.pop();
}
operators.pop(); // 弹出左括号
}
else if (isOperator(ch)) {
while (!operators.empty() && getPriority(operators.top()) >= getPriority(ch)) {
postfix += operators.top();
operators.pop();
}
operators.push(ch);
}
else { // 操作数
postfix += ch;
}
}
}
while (!operators.empty()) {
postfix += operators.top();
operators.pop();
}
return postfix;
}
// 计算后缀表达式的结果
double evaluatePostfix(string postfix) {
stack<double> operands; // 操作数栈
for (char ch : postfix) {
if (!isOperator(ch)) { // 操作数
operands.push(ch - '0'); // 字符转数字
}
else { // 运算符
double operand2 = operands.top();
operands.pop();
double 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() {
string infix;
cin >> infix;
string postfix = infixToPostfix(infix);
cout << "转换的后缀表达式为:" << postfix << endl;
double result = evaluatePostfix(postfix);
cout << "计算结果为:" << result << endl;
return 0;
}
修改后的代码会在读取输入时排除掉字符 ‘#‘,从而不会输出它。
内容由零声教学AI助手提供,问题来源于学员提问




