这个题可以普通的用数组进行求解,也可以像本文一样采取中缀转后缀的方式,然后再进行计算
主要注意的地方是:题目中的乘法用的是字母x,因为这个原因改了一个晚上代码,不知道这样设置为什么。
主要代码如下:
#include <iostream>
#include <stack>
using namespace std;
int transform(char a)
{
if (a == '0') return 0;
if (a == '1') return 1;
if (a == '2') return 2;
if (a == '3') return 3;
if (a == '4') return 4;
if (a == '5') return 5;
if (a == '6') return 6;
if (a == '7') return 7;
if (a == '8') return 8;
if (a == '9') return 9;
}
int main(void)
{
int n;
cin >> n;
int result[100];//用来存放结果,1表示yes,0表示no
stack<char>ch;
char a[100][7];
char r[7];
for (int i = 0; i < n; i++)
{
//cout << "****************************第" << i << "次大循环进行输入" << endl;
//每一个进行一次处理
int f = 0;
cin >> a[i];
for (int j = 0; j < 7; j++)
{
//cout << "进入第" << j << "次循环" << endl;
//cout << "处理" << a[i][j] << " " << endl;
if (a[i][j] == '+' || a[i][j] == '-')
{
// cout << "匹配上+ /-" << endl;
if (ch.empty()) { ch.push(a[i][j]); }
else {
while (!ch.empty() && (ch.top() == '+' || ch.top() == '-' || ch.top() == '*' || ch.top() == '/'||ch.top()=='x'))
{
//cout << "检测到一个比加好等级小的" << endl;
r[f] = ch.top();
ch.pop();
f++;
}
ch.push(a[i][j]);
}
}
else if (a[i][j] == '*' || a[i][j] == '/'||a[i][j] == 'x')
{
//cout << "打印栈顶"<<ch.top()<<endl;
while (!ch.empty() && ( ch.top() == '*' || ch.top() == '/' || ch.top() == 'x'))
{
// cout << "检测到一个同级的" << endl;
r[f] = ch.top();
ch.pop();
f++;
}
ch.push(a[i][j]);
}
else
{
r[f] = a[i][j];
f++;
}
}
//cout << "输出第一次的f " << f << endl;
while (!ch.empty())
{
// cout << "不为空" << ch.top() << endl;
r[f] = ch.top();
ch.pop();
f++;
}
//cout <<"长度为"<< f<<endl;
/*for (int y = 0; y <= f; y++)
{
cout << r[y] << endl;
}*/
int jie;//用来存储当前次的结果
stack<int>w;
for (int p = 0; p < f; p++)
{
if (r[p] == '+')
{
// cout << "做加法" << endl;
int a = w.top();
w.pop();
int b = w.top();
w.pop();
jie = b + a;
w.push(jie);
// cout << jie << "中间结果" << endl;
}
else if (r[p] == '-')
{
// cout << "做减法" << endl;
int a = w.top();
w.pop();
int b = w.top();
w.pop();
jie = b - a;
w.push(jie);
}
else if (r[p] == '*'||r[p]=='x')
{
// cout << "做乘法" << endl;
int a = w.top();
// cout << "第一个乘数" << a << endl;
w.pop();
int b = w.top();
// cout << "第2个乘数" << b << endl;
w.pop();
jie = b * a;
// cout << "这时结果为" << jie << endl;
w.push(jie);
}
else if (r[p] == '/')
{
int a = w.top();
w.pop();
int b = w.top();
w.pop();
jie = b / a;
w.push(jie);
}
else
{
int aa = transform(r[p]);
w.push(aa);
}
// cout <<"++++++"<< w.top();
}
jie = w.top();
//cout << "输出结果" << jie << endl;
if (jie == 24)
{
result[i] = 1;
}
else {
result[i] = 0;
}
}
for (int m = 0; m < n; m++)
{
if (result[m] == 1)
cout << "Yes" << endl;
else if (result[m] == 0)
cout << "No" << endl;
}
system("pause");
return 0;
}
运行结果为: