代码:
#include <iostream>
using namespace std;
int jia(int a, int b) { return a + b; }
int jian(int a, int b) { return a - b; }
int cheng(int a, int b) { return a * b; }
int chu(int a, int b) { if (b == 0 || a % b != 0) { return -10000000; } return a / b; };
int (*op[4])(int a, int b){jia, jian,
cheng, chu};
char fu[4] = { '+','-','*','/' };
int pjia(int a, int b) { cout << a <<"+"<< b << "=" << a + b << endl; return a + b; }
int pjian(int a, int b) { cout << a << "-" << b << "=" << a - b << endl; return a - b; }
int pcheng(int a, int b) { cout << a << "*" << b << "=" << a * b << endl; return a * b; }
int pchu(int a, int b) { cout << a << "/" << b << "=" << a / b << endl; return a / b; }
int(*println[4])(int a, int b) { pjia, pjian,
pcheng, pchu };
int num0[4];
void dian24(int a,int b,int c,int d)
{
for (int i = 0; i < 4;
i++) //ab
{
for (int j = 0; j < 4;
j++) //bc
{
for (int k = 0; k < 4;
k++) //cd
{
int result;
//123
result
= op[k](op[j](op[i](a, b), c), d);
if (result == 24)
{
println[k](println[j](println[i](a, b), c), d);
return;
}
//213
result
= op[k](op[j](a, op[i](b, c)), d);
if (result == 24)
{
println[k](println[j](a, println[i](b, c)), d);
return;
}
//231
result
= op[k](a, op[j](op[i](b, c), d));
if (result == 24)
{
println[k](a,
println[j](println[i](b, c), d));
return;
}
//312
result
= op[k](op[j](c, d),op[i](a, b));
if (result == 24)
{
result
= println[k](println[j](c, d), println[i](a, b));
return;
}
//132
result
= op[k](op[i](a, b), op[j](c, d));
if (result == 24)
{
println[k](println[i](a, b), println[j](c, d));
return;
}
//321
result
= op[k](a, op[j](b, op[i](c, d)));
if (result == 24)
{
println[k](a, println[j](b, println[i](c, d)));
return;
}
}
}
}
cout
<< "No
answer!" << endl;
return;
}
int main()
{
int a, b, c, d;
while (cin >> a >> b >> c >> d)
{
dian24(a,
b, c, d);
}
}
思路,24点问题由于个数较小可以使用暴力破解,把问题抽象为
a op1 b op2 c op3 d. op代表操作符.由于存在括号的原因,op1,op2,op3的运算顺序可能不同,因为只有3个方法,所以就穷举出来,有3!种方式。在这段代码中巧妙的运用了函数指针数组,这样可以让一个函数就算的结果成为另一个函数参数,而且因为是数组的原因,可以由形参i,j,k的变化调用不同的函数。
参考了博主:https://blog.csdn.net/vaintwyt/article/details/41478965