c++计算器中缀转后缀求值
时间: 2024-01-01 11:05:02 浏览: 60
以下是C++中实现中缀转后缀求值的示例代码:
```cpp
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
int getPriority(char op) {
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
else
return 0;
}
string infixToPostfix(string infix) {
stack<char> opStack;
stringstream postfix;
for (char c : infix) {
if (isdigit(c)) {
postfix << c;
} else if (c == '(') {
opStack.push(c);
} else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix << opStack.top();
opStack.pop();
}
opStack.pop(); // 弹出左括号
} else {
while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(c)) {
postfix << opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
while (!opStack.empty()) {
postfix << opStack.top();
opStack.pop();
}
return postfix.str();
}
int evaluatePostfix(string postfix) {
stack<int> numStack;
for (char c : postfix) {
if (isdigit(c)) {
numStack.push(c - '0');
} else {
int operand2 = numStack.top();
numStack.pop();
int operand1 = numStack.top();
numStack.pop();
switch (c) {
case '+':
numStack.push(operand1 + operand2);
break;
case '-':
numStack.push(operand1 - operand2);
break;
case '*':
numStack.push(operand1 * operand2);
break;
case '/':
numStack.push(operand1 / operand2);
break;
}
}
}
return numStack.top();
}
int main() {
string infixExpression;
cout << "请输入中缀表达式:"; cin >> infixExpression;
string postfixExpression = infixToPostfix(infixExpression);
cout << "后缀表达式:" << postfixExpression << endl;
int result = evaluatePostfix(postfixExpression);
cout << "计算结果:" << result << endl;
return 0;
}
```