p1449 后缀表达式
时间: 2023-10-19 14:08:59 浏览: 49
对于后缀表达式的求值,可以通过使用栈来实现。下面是一个求解后缀表达式的示例代码:
```C++
#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
double evaluatePostfix(string postfix) {
stack<double> operandStack;
for (char c : postfix) {
if (isdigit(c)) {
operandStack.push(c - '0');
} else if (isOperator(c)) {
double operand2 = operandStack.top();
operandStack.pop();
double operand1 = operandStack.top();
operandStack.pop();
switch (c) {
case '+':
operandStack.push(operand1 + operand2);
break;
case '-':
operandStack.push(operand1 - operand2);
break;
case '*':
operandStack.push(operand1 * operand2);
break;
case '/':
if (operand2 != 0) {
operandStack.push(operand1 / operand2);
} else {
cout << "Error: Division by zero!" << endl;
return 0.0;
}
break;
}
}
}
if (!operandStack.empty()) {
return operandStack.top();
} else {
cout << "Error: Invalid postfix expression!" << endl;
return 0.0;
}
}
int main() {
string postfix;
cout << "Enter a postfix expression: ";
cin >> postfix;
double result = evaluatePostfix(postfix);
cout << "Result: " << result << endl;
return 0;
}
```