题目:给你4个正整数,这4个正整数的范围是1到13.问这四个数可否通过加减乘除的不同组合(可以使用括号)得到最终结果24.假如有这样的组合,那么给出这种组合的具体表达式。
分析:最简单直接的办法就是穷举每一个组合,及计算每一种组合的结果,看其是否有结果24.
解决方法:可以从原来数组中任意取出两个数,然后依次计算这两个数的加、减、乘、除,将计算结果放入原来的数组,并把取出来的两个数从原来数组中删除。依次规则进行,直到数组中只剩下一个数,这就是这个组合的运算结果。以上步骤中“任意取两个数”其实对应于任意数的组合,并加括号。
下面是本题的一个C语言实现:
#include<stdio.h>
#include<math.h>
#include<string.h>
int is_this_right(double* array,char result[][50],int n)
{
if(n==1)
{
if(fabs(array[0]-24.0)<0.001) //因为有除法,所以用实数存结果,并允许有一定误差
{
printf("%s\n",result[0]);
return 1;
}
else
return 0;
}
int i,j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
double a,b,temp;
char s_a[50]={},s_b[50]={},s_temp[50]={};
a=array[i];
strcpy(s_a,result[i]);
b=array[j];
strcpy(s_b,result[j]);
array[j]=array[n-1];
strcpy(result[j],result[n-1]);
temp=a+b;
strcpy(s_temp,"(");
strcat(s_temp,s_a);
strcat(s_temp,"+");
strcat(s_temp,s_b);
strcat(s_temp,")");
array[i]=temp;
strcpy(result[i],s_temp);
if(is_this_right(array,result,n-1))
return 1;
temp=a-b;
strcpy(s_temp,"(");
strcat(s_temp,s_a);
strcat(s_temp,"-");
strcat(s_temp,s_b);
strcat(s_temp,")");
array[i]=temp;
strcpy(result[i],s_temp);
if(is_this_right(array,result,n-1))
return 1;
temp=b-a;
strcpy(s_temp,"(");
strcat(s_temp,s_b);
strcat(s_temp,"-");
strcat(s_temp,s_a);
strcat(s_temp,")");
array[i]=temp;
strcpy(result[i],s_temp);
if(is_this_right(array,result,n-1))
return 1;
temp=a*b;
strcpy(s_temp,"(");
strcat(s_temp,s_a);
strcat(s_temp,"*");
strcat(s_temp,s_b);
strcat(s_temp,")");
array[i]=temp;
strcpy(result[i],s_temp);
if(is_this_right(array,result,n-1))
return 1;
temp=a/b;
strcpy(s_temp,"(");
strcat(s_temp,s_a);
strcat(s_temp,"/");
strcat(s_temp,s_b);
strcat(s_temp,")");
array[i]=temp;
strcpy(result[i],s_temp);
if(is_this_right(array,result,n-1))
return 1;
temp=b/a;
strcpy(s_temp,"(");
strcat(s_temp,s_b);
strcat(s_temp,"/");
strcat(s_temp,s_a);
strcat(s_temp,")");
array[i]=temp;
strcpy(result[i],s_temp);
if(is_this_right(array,result,n-1))
return 1;
array[i]=a;
strcpy(result[i],s_a);
array[j]=b;
strcpy(result[j],s_b);
}
return 0;
}
int main()
{
int i;
double array_of_four_numbers[4];
char result[4][50];
printf("please input the four numbers:\n");
scanf("%lf",array_of_four_numbers);
scanf("%lf",array_of_four_numbers+1);
scanf("%lf",array_of_four_numbers+2);
scanf("%lf",array_of_four_numbers+3);
sprintf(result[0],"%lf",array_of_four_numbers[0]);
sprintf(result[1],"%lf",array_of_four_numbers[1]);
sprintf(result[2],"%lf",array_of_four_numbers[2]);
sprintf(result[3],"%lf",array_of_four_numbers[3]);
if(!is_this_right(array_of_four_numbers,result,4))
printf("can not get the result 24 use the four number inputed.\n");
return 0;
}