计算后缀表达式c++
时间: 2023-12-20 15:06:12 浏览: 78
以下是C++计算后缀表达式的示例代码:
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int evaluatePostfix(string exp) {
stack<int> stack;
for (int i = 0; i < exp.length(); i++) {
if (isdigit(exp[i])) {
int num = 0;
while (isdigit(exp[i])) {
num = num * 10 + (int)(exp[i] - '0');
i++;
}
i--;
stack.push(num);
} else {
int val1 = stack.top();
stack.pop();
int val2 = stack.top();
stack.pop();
switch (exp[i]) {
case '+':
stack.push(val2 + val1);
break;
case '-':
stack.push(val2 - val1);
break;
case '*':
stack.push(val2 * val1);
break;
case '/':
stack.push(val2 / val1);
break;
}
}
}
return stack.top();
}
int main() {
string exp = "23+4*5-";
cout << "Postfix Expression: " << exp << endl;
cout << "Result: " << evaluatePostfix(exp) << endl;
return 0;
}
```
阅读全文