帮我排错 #include <iostream> #include <stack> #include <cstring> using namespace std; int n; int solve(string s) { stack<int> st; char sign = '+'; int num = 0; int ans = 0; for(int i = 0; i < s.size(); i++) { if(s[i] == ' ') { continue; } if(s[i] >= '0' && s[i] <= '9') { num = num*10+(s[i]-'0'); } if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || i == s.size()-1) { if(sign == '+') { st.push(num); } if(sign == '-') { st.push(-num); } if(sign == '*') { st.top() *= num; } if(sign == '/') { st.top() *= num; } sign = s[i]; num = 0; } } while (!st.empty()) { ans += st.top(); st.pop(); } return ans; } int main() { string s; getline(cin, s); cout << solve(s) << endl; return 0; }
时间: 2023-12-03 15:05:28 浏览: 69
在计算除法时,代码中写成了 `st.top() *= num`,实际应该是 `st.top() /= num`。
修改后的代码如下所示:
```cpp
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int n;
int solve(string s) {
stack<int> st;
char sign = '+';
int num = 0;
int ans = 0;
for(int i = 0; i < s.size(); i++) {
if(s[i] == ' ') {
continue;
}
if(s[i] >= '0' && s[i] <= '9') {
num = num*10+(s[i]-'0');
}
if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || i == s.size()-1) {
if(sign == '+') {
st.push(num);
}
if(sign == '-') {
st.push(-num);
}
if(sign == '*') {
st.top() *= num;
}
if(sign == '/') {
st.top() /= num; // 修改这一行
}
sign = s[i];
num = 0;
}
}
while (!st.empty()) {
ans += st.top();
st.pop();
}
return ans;
}
int main() {
string s;
getline(cin, s);
cout << solve(s) << endl;
return 0;
}
```
阅读全文