我来解答下,望采纳
- 首先,需要定义变量用于存储四个数字,即a、b、c和d。
- 然后,定义函数calc(),该函数用于计算+、-、*、/四种运算的指定顺序的结果,并使用变量存储结果。
- 再者,使用递归的方式,列举出每种可能的运算符排序,并调用calc()函数求解。
- 最后,循环遍历结果,判断是否有结果等于24,如果有,则输出Yes,否则输出No。
代码示例:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int a, b, c, d; // 存放四个数字
// calc()用于计算+、-、*、/四种运算的顺序
// operators用于存放当前运算符顺序
// n表示已经选取的运算符个数
double calc(int a, int b, int c, int d, char operators[], int n)
{
if(n == 4) {
int num[4] = {a, b, c, d};
double ans = num[0];
for(int i=1;i<4;i++) {
if(operators[i-1] == '+') {
ans += num[i];
} else if(operators[i-1] == '-') {
ans -= num[i];
} else if(operators[i-1] == '*') {
ans *= num[i];
} else if(operators[i-1] == '/') {
ans /= num[i];
}
}
return ans;
}
double ans = 0.0;
// +
operators[n] = '+';
ans = calc(a, b, c, d, operators, n+1);
if(ans == 24.0) return ans;
// -
operators[n] = '-';
ans = calc(a, b, c, d, operators, n+1);
if(ans == 24.0) return ans;
// *
operators[n] = '*';
ans = calc(a, b, c, d, operators, n+1);
if(ans == 24.0) return ans;
// /
operators[n] = '/';
ans = calc(a, b, c, d, operators, n+1);
if(ans == 24.0) return ans;
return 0.0;
}
int main()
{
cin >> a >> b >> c >> d;
char operators[3]; //存放三个运算符
double ans = calc(a, b, c, d, operators, 0);
if(ans == 24.0) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
```