之前做过一道相似的题目,只不过是没有分数形式,并且顺序不能打乱。
这里,其实方法就是枚举,遍历所有符号(4^3次方种符号情况),遍历所有顺序(四个数进行全排列),最重要的就是加括号的情况有5种,遍历这些情况即可。这里虽然要求有分数,但是我还是用double,然后控制精度水过了。其实改成分数,分别保存分子和分母的数值才是最正确的计算方法。
直接上代码,比较简单:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
#define exp 1e-6
char operators[4] = {'+', '-', '*', '/'};
double calc( double a, int operatorr, double b)
{
switch (operators[operatorr])
{
case '+':
return a + b;
break;
case '-':
return a - b;
break;
case '*':
return a * b;
break;
case '/':
return a / b;
break;
}
}
int calculator(int i, int j, int k, double a, double b, double c, double d)//5种加括号的方式
{
if (fabs(calc(calc(a, i, b),j,calc(c, k, d)) - 24.0) < exp)
{
printf("(%.0lf%c%.0lf)%c(%.0lf%c%.0lf)\n",a, operators[i], b, operators[j], c, operators[k], d);
return 1;
}
if (fabs(calc(calc(calc(a, i, b), j, c), k, d) - 24.0) < exp)
{
printf("((%.0lf%c%.0lf)%c%.0lf)%c%.0lf)\n",a, operators[i], b, operators[j], c, operators[k], d);
return 1;
}
if (fabs(calc(calc(a, i, calc(b, j, c)), k, d) - 24.0) < exp)
{
printf("(%.0lf%c(%.0lf%c%.0lf))%c%.0lf)\n",a, operators[i], b, operators[j], c, operators[k], d);
return 1;
}
if (fabs(calc(a, i, calc(calc(b, j, c), k, d)) - 24.0) < exp)
{
printf("%.0lf%c((%.0lf%c%.0lf)%c%.0lf)\n",a, operators[i], b, operators[j], c, operators[k], d);
return 1;
}
if (fabs(calc(a, i, calc(b, j, calc(c, k, d))) - 24.0) < exp)
{
printf("%.0lf%c(%.0lf%c(%.0lf%c%.0lf))\n",a, operators[i], b, operators[j], c, operators[k], d);
return 1;
}
return 0;
}
int main()
{
double a,b,c,d;
while (scanf("%lf %lf %lf %lf", &a, &b, &c, &d) != EOF)
{
int p[4];
p[0] = a;
p[1] = b;
p[2] = c;
p[3] = d;
for (int i = 0; i < 4; ++ i)//遍历所有符号
{
for(int j = 0; j < 4; ++ j)
{
for(int k = 0; k < 4; ++ k)
{
do
{
if(calculator(i,j,k,p[0],p[1],p[2],p[3]))
goto success;
} while (next_permutation(p,p+4));//遍历所有排列(4个数所有位置情况)
}
}
}
success:
continue;
}
return 0;
}