#include
#include
#include
#define LING1E-6
#define CONT4
#define VOLUE24
float number[CONT];
char expression[CONT][20] ;
bool m_judge = false; //判断是否有解。
int count = 0;
void Find(int n)
{
int i = 0, j = 0;
if (n == 1)
{
if ( fabs(number[0] - 24) <= LING)
{
for (i = 0; i < 20; i++)
{
printf("%c", expression[0][i]) ;
}
printf("\t\t") ;
m_judge = true;
count ++;
if((count % 2)==0) //使输出时每行三个表达式
printf("\n") ;
}
else
{ }
}
for(i = 0; i < n; i++)//查找
{
for (j = i + 1; j < n; j++)//与其后面的查找进行计算
{
float a, b;
char expressiona[20], expressionb[20];
a = number[i] ;
b = number[j] ;
number[j] = number[n - 1];
strcpy(expressiona, expression[i]) ;
strcpy(expressionb, expression[j]) ;
strcpy(expression[j], expression[n - 1]) ;
sprintf(expression[i], "(%s+%s)", expressiona, expressionb) ;
number[i] = a + b;
Find(n-1);
///
sprintf(expression[i], "(%s-%s)", expressiona, expressionb) ;
number[i] = a - b;
Find(n-1);
sprintf(expression[i], "(%s-%s)", expressionb, expressiona) ;
number[i] = b - a;
Find(n-1);
sprintf(expression[i], "(%s*%s)", expressiona, expressionb) ;
number[i] = a * b;
Find(n-1);
if (b != 0)
{
sprintf(expression[i], "(%s/%s)", expressiona, expressionb) ;
number[i] = a / b;
Find(n-1);
}
if (a != 0)
{
sprintf(expression[i], "(%s/%s)", expressionb, expressiona) ;
number[i] = b / a;
Find(n-1);
}
number[i] = a;// 最后一层的Find(2)调用完成后将a重新赋值给number[i]即number[0]
number[j] = b;// 最后一层的Find(2)调用完成后将b重新赋值给nubmer[j]即number[1]
strcpy(expression[i], expressiona) ;
strcpy(expression[j], expressionb) ;
}
}
}
int main()
{
int i, j ;
printf("请输入四个数:\n") ;
for (i = 0; i < CONT; i++)
{
char ch[20], s;
int a ;
printf("第%d个数:", i+1) ;
scanf("%f", &number[i]) ;
a = (int)number[i] ;
s = char(a + 48);
ch[0] = s ;
for (j = 1; j < 20; j++)
{
ch[j] = 0 ;
}
strcpy(expression[i], ch) ;
}
printf("\n") ;
Find(CONT) ;
if(m_judge==true)
{
printf("\n\n成功!\n") ;
printf("总共的计算方法共有:%d\n", count) ;
}
else
{
printf("失败!") ;
}
return 0;
}