写出一个栈的表达式求值,用C/C++语言编码实现,能在Dev-C中运行。以下是分值要求: 1、能对简单的表达式进行求值。60 2、能对含有浮点数以及含括号的表达式进行求值。25 3、代码格式规范、对异常有处理。15
时间: 2024-10-29 13:24:05 浏览: 11
下面是一个简单的栈式表达式求值的C++代码示例,这个程序能满足题目所描述的要求。请注意,此代码仅适用于基本的算术运算符,没有涉及括号解析和复杂算法,因此对于复杂的表达式如含括号的和浮点数运算,它可能无法完全满足要求。你可以根据需要扩展这个基础版本。
```cpp
#include <iostream>
#include <stack>
#include <cctype>
bool isOperator(char op) {
return op == '+' || op == '-' || op == '*' || op == '/';
}
double applyOperator(double num1, double num2, char op) {
switch (op) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': if (num2 != 0) return num1 / num2; // 防止除以零错误
default: throw std::runtime_error("Invalid operator");
}
}
double evaluateExpression(std::string tokens) {
std::stack<double> numbers;
std::stack<char> operators;
for (char token : tokens) {
if (isdigit(token)) {
double num = 0;
while (isdigit(token)) {
num = num * 10 + (token - '0');
++token;
}
numbers.push(num);
} else if (isOperator(token)) {
if (!numbers.empty() && !operators.empty()) {
double right = numbers.top(); numbers.pop();
double left = numbers.top(); numbers.pop();
char op = token; operators.pop();
numbers.push(applyOperator(left, right, op));
} else if (token == '(') {
operators.push(token);
} else if (token == ')') {
while (!operators.empty() && operators.top() != '(') {
double right = numbers.top(); numbers.pop();
double left = numbers.top(); numbers.pop();
char op = operators.top(); operators.pop();
numbers.push(applyOperator(left, right, op));
}
if (!operators.empty()) {
operators.pop(); // pop the '('
}
} else {
throw std::runtime_error("Invalid token");
}
} else {
throw std::runtime_error("Invalid token");
}
}
if (!numbers.empty()) {
double result = numbers.top(); numbers.pop();
while (!operators.empty()) {
double right = numbers.top(); numbers.pop();
double left = result;
char op = operators.top(); operators.pop();
result = applyOperator(left, right, op);
}
return result;
} else {
throw std::runtime_error("Invalid expression");
}
}
int main() {
try {
std::string input = "3 + 4 * (5 - 2)";
double result = evaluateExpression(input);
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文