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

实现一个简单的逆波兰表达式(RPN,Reverse Polish Notation)计算器,核心在于利用栈结构来处理操作数和运算符。RPN 表达式不需要括号来指定运算顺序,只要从左到右扫描表达式,遇到数字就入栈,遇到运算符就弹出两个操作数进行计算,结果再压回栈中。
RPN 表达式的格式是“操作数 操作数 运算符”,例如中缀表达式 3 + 4 在 RPN 中写作 3 4 +。更复杂的例子:(3 + 4) * 5 转换为 RPN 是 3 4 + 5 \*。
计算过程如下:
C++ 标准库中的 std::stack 非常适合实现 RPN 计算器。以下是核心计算函数的实现:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <stack>
#include <sstream>
#include <stdexcept>
<p>double evaluateRPN(const std::string& expression) {
std::stack<double> operands;
std::istringstream iss(expression);
std::string token;</p><pre class='brush:php;toolbar:false;'>while (iss >> token) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
if (operands.size() < 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。
这个实现已经可以处理大多数常见情况,但若要增强健壮性,可以考虑以下几点:
基本上就这些。RPN 计算器的关键是理解“后进先出”的操作逻辑,用栈自然地模拟计算流程,代码简洁且易于维护。
以上就是c++++怎么实现一个简单的逆波兰表达式计算器_C++中解析与计算RPN表达式的实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号