写c++代码 字符串S中只存在`*`,`/`两种运算符 - 除运算符外,S中仅包含数字字符`0`~`9` - 序列所有运算均合法,不会存在错误运算 - S中参与运算的原数字不会超过 int 范围 输出计算出值
时间: 2023-08-12 09:16:19 浏览: 40
好的,这里提供一个使用栈实现的 C++ 代码:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int calculate_expression(string S) {
stack<int> st;
for (char c : S) {
if (isdigit(c)) {
st.push(c - '0'); // 将字符转换为数字
} else if (c == '*') {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
st.push(a * b);
} else if (c == '/') {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
st.push(a / b);
}
}
return st.top();
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string S;
cin >> S;
int res = calculate_expression(S);
cout << res << endl;
}
return 0;
}
```
这里使用了 `stl` 中的 `stack` 来实现栈,代码中的注释已经解释了每一行的作用。注意在将字符转换为数字时需要减去字符 '0' 的 ASCII 码值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)