答案是利用栈结构实现逆波兰表达式计算,通过从左到右扫描表达式,数字入栈、运算符弹出两个操作数进行运算后将结果压栈,最终栈顶即为结果。

实现一个简单的逆波兰表达式(RPN,Reverse Polish Notation)计算器,核心在于利用栈结构来处理操作数和运算符。RPN 表达式不需要括号来指定运算顺序,只要从左到右扫描表达式,遇到数字就入栈,遇到运算符就弹出两个操作数进行计算,结果再压回栈中。
理解 RPN 的基本规则
RPN 表达式的格式是“操作数 操作数 运算符”,例如中缀表达式 3 + 4 在 RPN 中写作 3 4 +。更复杂的例子:(3 + 4) * 5 转换为 RPN 是 3 4 + 5 \*。
计算过程如下:
- 读取 3 → 压入栈
- 读取 4 → 压入栈
- 读取 + → 弹出 4 和 3,计算 3+4=7,压入 7
- 读取 5 → 压入栈
- 读取 \* → 弹出 5 和 7,计算 7\*5=35
- 最终栈中只剩一个值:35,即结果
使用 std::stack 实现计算逻辑
C++ 标准库中的 std::stack 非常适合实现 RPN 计算器。以下是核心计算函数的实现:
立即学习“C++免费学习笔记(深入)”;
#include#include #include #include double evaluateRPN(const std::string& expression) { std::stack
operands; std::istringstream iss(expression); std::string token; while (iss >> token) { if (token == "+" || token == "-" || token == "*" || token == "/") { if (operands.size() zuojiankuohaophpcn 2) { throw std::runtime_error("invalid RPN expression: not enough operands"); } double b = operands.top(); operands.pop(); double a = operands.top(); operands.pop(); double result = 0; if (token == "+") result = a + b; else if (token == "-") result = a - b; else if (token == "*") result = a * b; else if (token == "/") { if (b == 0) throw std::runtime_error("division by zero"); result = a / b; } operands.push(result); } else { try { double num = std::stod(token); operands.push(num); } catch (...) { throw std::runtime_error("invalid token: " + token); } } } if (operands.size() != 1) { throw std::runtime_error("invalid RPN expression"); } return operands.top();}
测试与使用示例
写一个简单的主函数来测试上述实现:
int main() {
std::string expr = "3 4 + 5 *";
try {
double result = evaluateRPN(expr);
std::cout << "Result: " << result << std::endl; // 输出 35
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
支持浮点数和负数,例如表达式 "-3 4 +" 会正确计算为 1。
注意事项与扩展建议
这个实现已经可以处理大多数常见情况,但若要增强健壮性,可以考虑以下几点:
- 添加对更多运算符的支持,如幂运算 ^、取模 % 等
- 支持一元运算符(如负号),需要额外判断上下文
- 输入预处理:去除多余空格、支持 tab 分隔
- 返回错误位置信息以便调试
基本上就这些。RPN 计算器的关键是理解“后进先出”的操作逻辑,用栈自然地模拟计算流程,代码简洁且易于维护。









