写一个用stack类实现四则运算的代码
时间: 2024-05-07 11:16:29 浏览: 13
好的,以下是用 stack 类实现四则运算的代码示例:
```
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int calculate(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
int evalRPN(string tokens) {
stack<int> s;
for (int i = 0; i < tokens.size(); i++) {
char c = tokens[i];
if (isdigit(c)) {
int num = 0;
while (isdigit(tokens[i])) {
num = num * 10 + (tokens[i] - '0');
i++;
}
i--;
s.push(num);
}
else if (c == '+' || c == '-' || c == '*' || c == '/') {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(calculate(a, b, c));
}
}
return s.top();
}
int main() {
string s = "3 4 + 5 -"; // 表达式 3 + 4 - 5
cout << evalRPN(s) << endl; // 输出结果为 2
return 0;
}
```
希望本代码对您有帮助。如果您有任何其他问题,请直接问我!现在请问你有什么其他问题吗?
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)