#include<iostream> #include<stack> #include<string> using namespace std; stack<int>s1; stack<char>s2; int sum; int opera(int a,char b,int c) { if (b == 'x')return a * c; else if (b == '/')return a / c; else if (b == '+')return a + c; else if (b == '-')return a - c; } int calculate(string s) { sum = 0; for (int i = 0; i < 7; i++) { if (i == 1 || i == 3 || i == 5) { if (s[i] == '+' || s[i] == '-') { s2.push(s[i]); } else if (s[i] == 'x' || s[i] == '/') { int top = s1.top(); int temp = opera(top, s[i], s[i + 1]); s1.push(temp); i++; } } else s1.push(s[i] - '0'); } int tmp1[4], tmp2[3]; int index1 = 3; int index2 = 2; while (!s1.empty()) { tmp1[index1--] = s1.top(); s1.pop(); } while (!s2.empty()) { tmp2[index2--] = s2.top(); s2.pop(); } for (int i = 0; i < 4; i++) { sum += opera(tmp1[i], tmp2[i], tmp1[i + 1]); } return sum; } int main() { int n; cin >> n;//n行整数 string s ; for (int i = 0; i < n; i++) { cin >> s; calculate(s); if (sum == 24) { cout << "Yes" << endl; } else cout << "No" << endl; } system("pause"); }修改以上代码
时间: 2023-11-27 13:55:00 浏览: 58
以下是修改后的代码,主要修改了calculate函数中的逻辑:
```c++
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack<int> s1;
stack<char> s2;
int opera(int a, char b, int c) {
if (b == 'x') return a * c;
else if (b == '/') return a / c;
else if (b == '+') return a + c;
else if (b == '-') return a - c;
}
int calculate(string s) {
// 清空栈
while (!s1.empty()) s1.pop();
while (!s2.empty()) s2.pop();
int sum = 0;
for (int i = 0; i < 7; i++) {
if (i == 1 || i == 3 || i == 5) {
if (s[i] == '+' || s[i] == '-') {
s2.push(s[i]);
} else if (s[i] == 'x' || s[i] == '/') {
int top = s1.top();
s1.pop(); // 弹出栈顶元素
int temp = opera(top, s[i], s[i + 1]);
s1.push(temp);
i++;
}
} else {
s1.push(s[i] - '0');
}
}
// 计算栈中剩余的元素
while (!s2.empty()) {
int a = s1.top();
s1.pop();
int b = s1.top();
s1.pop();
char op = s2.top();
s2.pop();
s1.push(opera(b, op, a));
}
return s1.top(); // 返回栈中最后剩余的元素
}
int main() {
int n;
cin >> n;
string s;
for (int i = 0; i < n; i++) {
cin >> s;
if (calculate(s) == 24) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}
```
修改的主要内容如下:
1. 在calculate函数中加入了清空栈的操作,保证每次计算之前栈中没有残留元素。
2. 修改了计算逻辑,先将字符串中的元素依次入栈,然后按照运算符的优先级进行计算,最终返回栈中剩余的元素。
3. 在主函数中直接调用calculate函数,并根据返回值判断是否等于24输出结果。
阅读全文