#define NUM_SIZE 4
#define OP_SIZE 4
const double neglible = 10e-7;
void twentyFour(int x, int y, int z, int a);
bool tryTwentyFour(int* n, double(*op[])(double, double));
//基本运算
double add(double a, double b);
double sub(double a, double b);
double mul(double a, double b);
double divs(double a, double b);
void twentyFour(int x, int y, int z, int a)
{
int number[] = { x, y, z, a };
double(*op[4])(double a, double b) = { add, sub, mul, divs };
bool judge = false;
sort(number, number + 4);
while (next_permutation(number, number + 4)) //取所有的可能排列
{
if (tryTwentyFour(number, op))
judge = true;
}
if (!judge)
cout << "这四个数无计算结果" << endl;
else
cout << "这四个数可以计算出24点" << endl;
}
bool tryTwentyFour(int* n, double(*op[])(double, double))
{
bool judge = false;
for (int i = 0; i < OP_SIZE; i++)//穷举所有的计算
{
for (int j = 0; j < OP_SIZE; j++)
{
for (int k = 0; k < OP_SIZE; k++) //五种不同的计算顺序
{
if (abs(op[k](op[j](op[i](n[0], n[1]), n[2]), n[3]) - 24) <= neglible)//差的很少,认为是24点
judge = true;
if (abs((op[k](op[i](op[j](n[1], n[2]), n[0]), n[4])) - 24) <= neglible)
judge = true;
if (abs(op[j](op[i](n[0], n[1]), op[k](n[2], n[3])) - 24) <= neglible)
judge = true;
if (abs(op[i](n[0], op[k](op[j](n[1], n[2]), n[3])) - 24) <= neglible)
judge = true;
if (abs(op[i](n[0], op[j](n[1], op[k](n[2], n[3]))) - 24) <= neglible)
judge = true;
}
}
}
return judge;
}
double add(double a, double b)
{
return a + b;
}
double sub(double a, double b)
{
return a - b;
}
double mul(double a, double b)
{
return a * b;
}
double divs(double a, double b)
{
if (b != 0)
return a / b;
else
return INT_MIN;
}
/*下面是测试 */
int main()
{
cout << "请输入4个数字(1-10):" << endl;
int x, y, z, a;
cin >> x >> y >> z >> a;
twentyFour(x, y, z, a);
return 0;
}