使用cpp 实现简易计算器,包括后缀表达式计算、中缀表达式计算和中缀转后缀表达式。其中,操作符包括加、减、乘、除,操作数为0-9之间的整数。
时间: 2024-10-22 20:25:28 浏览: 67
在C++中,我们可以使用递归解析法来实现一个基本的计算器,支持后缀表达式(也称逆波兰表达式,RPN)和中缀表达式。下面我会分别介绍这三种功能的实现。
1. **后缀表达式计算**(也称为Reverse Polish Notation,RPN)
```cpp
#include <vector>
#include <stack>
#include <sstream>
double evalPostfix(std::vector<std::string>& tokens) {
double operand1, operand2;
for (const auto& token : tokens) {
if (isdigit(token)) {
operand1 = std::stod(token);
} else {
operand2 = std::stod(tokens.back());
tokens.pop_back();
switch (token) {
case "+":
tokens.push_back(std::to_string(operand1 + operand2));
break;
case "-":
tokens.push_back(std::to_string(operand1 - operand2));
break;
case "*":
tokens.push_back(std::to_string(operand1 * operand2));
break;
case "/":
tokens.push_back(std::to_string(operand1 / operand2));
break;
default:
throw std::runtime_error("Invalid operator");
}
}
}
if (tokens.size() != 1)
throw std::runtime_error("Invalid expression");
return std::stod(tokens[0]);
}
```
2. **中缀表达式计算**(需先转换成后缀表达式)
```cpp
void infixToPostfix(const std::string& infixExp, std::vector<std::string>& postfixExp) {
stack<char> operators;
std::istringstream iss(infixExp);
string token;
while (iss >> token) {
if (isdigit(token) || token == ".")
postfixExp.push_back(token);
else {
while (!operators.empty() && precedence(token) <= precedence(operators.top()))
postfixExp.push_back(operators.top()), operators.pop();
operators.push(token);
}
}
while (!operators.empty())
postfixExp.push_back(operators.top()), operators.pop();
reverse(postfixExp.begin(), postfixExp.end());
}
// 你需要提供一个 precedence 函数来比较运算符优先级
```
3. **中缀转后缀表达式**
上述代码已包含了从中缀表达式到后缀表达式的转换。
阅读全文
相关推荐

















