```c++
```#include<iostream>
#include<cmath>
using namespace std;
double a[5];
#define EPS 1e-6
bool isZero(double x) {
return fabs(x) <= EPS;
}
bool count24(double a[], int n) {
if (n == 1) {
if (isZero(a[0] - 24))
return true;
else
return false;
}
double b[5]
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++) {
int m = 0;
for (int k = 0; k < n; k++)
if (k != i && k != j)
b[m++] = a[k];
b[m] = a[i] + a[j];
if (count24(b, m + 1))
return true;
b[m] = a[i] - a[j];
if (count24(b, m + 1))
return true;
b[m] = a[j] - a[i];
if (count24(b, m + 1))
return true;
b[m] = a[i] * a[j];
if (count24(b, m + 1))
return true;
if (!isZero(a[j])) {
b[m] = a[i] / a[j];
if (count24(b, m + 1))
return true;
}
if (!isZero(a[i])) {
b[m] = a[j] / a[i];
if (count24(b, m + 1))
return true;
}
}
return false;
}
int main() {
double t;
while (cin>>t)
{
for (int i = 1; i < 4; i++)
cin >> a[i];
if (t == 0 && a[1] == 0 && a[2] == 0&&a[3]==0)break;
if (count24(a, 4))
cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
//为什么样例对,但答案不对呢?????
输入的 t 没赋值给 a[0]
我可以提供一种C++编写算24的求解器的思路,但对于每个能够用加、减、乘、除得到24的表达式的计算,需要实现一个运算符优先级分组的算法来解决。该程序可以使用递归函数Recursion,从15个值中选取任意4个值进行计算,并返回运算结果,再继续循环计算选取3个数、2个数、1个数的情况。 下面是大概的实现思路: 1. 定义一个队列,存储数列; 2. 将数列排列组合,即可得到所有可能的数字组合方式; 3. 定义一个函数,计算前三个数的结果; 4. 遍历所有数列,取出 1 个数,其余 3 个数组成新的数列; 5. 对新的数列遍历,取出其中 1 个数,将其余的 2 个数组成新的数列; 6. 重复上述操作,直至所有计算结束,得到运算结果; 7. 筛选出结果为 24 的运算式。
下面是大概的代码实现思路:
#include<iostream>
#include<queue>
using namespace std;
void recursion(queue<int> q)
{
if(q.size() == 1)
{
if(q.front() == 24)
cout << "equals 24" << endl;//处理结果
return;
}
double a, b, result;
int p, s;
int len = q.size();
for(int i = 0; i < len - 1; i++)
{
a = q.front(); q.pop();//每次取出首位元素
for(int j = i + 1; j < len; j++)
{
b = q.front(); q.pop();//每次取出首位元素
for(int k = 0; k < 6; k++)//进行+、-、*、/的运算
{
if(k == 0) result = a + b;
if(k == 1) result = a - b;
if(k == 2) result = b - a;
if(k == 3) result = a * b;
if(k == 4) {
if(b == 0)
{
q.push(a); q.push(b);
continue;
}
result = a / b;
}
if(k == 5) {
if(a == 0)
{
q.push(a); q.push(b);
continue;
}
result = b / a;
}
q.push(result);
recursion(q);
q.pop();
}
q.push(b);
}
q.push(a);
}
}
int main()
{
queue<int> q;
q.push(6);
q.push(6);
q.push(6);
q.push(6);//将要进行运算的四个数放入队列
recursion(q);//递归计算得到结果
return 0;
}
由于需要递归操作,需要注意的是防止栈溢出的问题,运算次数过多时可能会降低程序执行效率。 以上是本人大致的思路,如有疑问或更好的实现方式,可以进行拓展或修正。