主题:用递归法解24点,可以推广到N个数进行运算
#include<stdio.h>
#define N 4
#include<math.h>
float cun[N-1][3];
int q=0;
float f(int b,float m,float n) /*定义函数f,功能:对m和n进行四则运算,参数b代表四则运算法则*/
{
float c;
if(b==1)
c=m+n;
else if(b==2)
c=m-n;
else if(b==3)
c=m*n;
else if (b==4&&n!=0)
c=m/n;
else
c=-1000;
return (c);
}
void pf(int b,float m,float n) /*定义函数pf,功能:输出,参数b代表四则运算*/
{if(b==1)
printf("%.3f+%.3f=%.3f\t",m,n,f(1,m,n));
else if(b==2)
printf("%.3f-%.3f=%.3f\t",m,n,f(2,m,n));
else if(b==3)
printf("%.3f*%.3f=%.3f\t",m,n,f(3,m,n));
else if(b==4&&n!=0)
printf("%.3f/%.3f=%.3f\t",m,n,f(4,m,n));
}
int work(float a[],int b1[],int count,int p) /*定义函数work,参数p*/
{
int i,k,j,way;
int b2[N]={0};
float c[N];
if(p==0)
{if(fabs(a[0]-24)<1e-5)
q=1;
return 0;
}
if(count==-1)
{ for(way=1;way<5;way++)
{for(i=0;i<p+1;i++)
if(i==0)
{if(way==4&&a[b1[1]-1]==0)
goto end;
c[i]=f(way,a[b1[0]-1],a[b1[1]-1]);
}
else c[i]=a[b1[i+1]-1];
work(c,b1,p-1,p-1);
if(q==1)
{cun[N-p-1][0]=way;
cun[N-p-1][1]=a[b1[0]-1];
cun[N-p-1][2]=a[b1[1]-1];
return 0;
}
end:;
}
}
for(j=1;j<=p+1;j++)
{for(i=0;i<N;i++)
b2[i]=b1[i];
for(i=count+1;i<=p;i++)
if(b1[i]==j)
goto point;
b2[count]=j;
work(a,b2,count-1,p);
if(q==1)
return 0;
point:;
}
}
main()
{
int i,j,b[N];
char p;
float a[N];
do{ q=0;
for(i=0;i<N;i++)
scanf("%f",&a[i]);
work(a,b,N-1,N-1);
if(q==1)
for(i=0;i<N-1;i++)
pf(cun[i][0],cun[i][1],cun[i][2]);
else printf("No answer.");
scanf(" %c",&p);
} while(p!='n');
}
#define N 4
#include<math.h>
float cun[N-1][3];
int q=0;
float f(int b,float m,float n) /*定义函数f,功能:对m和n进行四则运算,参数b代表四则运算法则*/
{
float c;
if(b==1)
c=m+n;
else if(b==2)
c=m-n;
else if(b==3)
c=m*n;
else if (b==4&&n!=0)
c=m/n;
else
c=-1000;
return (c);
}
void pf(int b,float m,float n) /*定义函数pf,功能:输出,参数b代表四则运算*/
{if(b==1)
printf("%.3f+%.3f=%.3f\t",m,n,f(1,m,n));
else if(b==2)
printf("%.3f-%.3f=%.3f\t",m,n,f(2,m,n));
else if(b==3)
printf("%.3f*%.3f=%.3f\t",m,n,f(3,m,n));
else if(b==4&&n!=0)
printf("%.3f/%.3f=%.3f\t",m,n,f(4,m,n));
}
int work(float a[],int b1[],int count,int p) /*定义函数work,参数p*/
{
int i,k,j,way;
int b2[N]={0};
float c[N];
if(p==0)
{if(fabs(a[0]-24)<1e-5)
q=1;
return 0;
}
if(count==-1)
{ for(way=1;way<5;way++)
{for(i=0;i<p+1;i++)
if(i==0)
{if(way==4&&a[b1[1]-1]==0)
goto end;
c[i]=f(way,a[b1[0]-1],a[b1[1]-1]);
}
else c[i]=a[b1[i+1]-1];
work(c,b1,p-1,p-1);
if(q==1)
{cun[N-p-1][0]=way;
cun[N-p-1][1]=a[b1[0]-1];
cun[N-p-1][2]=a[b1[1]-1];
return 0;
}
end:;
}
}
for(j=1;j<=p+1;j++)
{for(i=0;i<N;i++)
b2[i]=b1[i];
for(i=count+1;i<=p;i++)
if(b1[i]==j)
goto point;
b2[count]=j;
work(a,b2,count-1,p);
if(q==1)
return 0;
point:;
}
}
main()
{
int i,j,b[N];
char p;
float a[N];
do{ q=0;
for(i=0;i<N;i++)
scanf("%f",&a[i]);
work(a,b,N-1,N-1);
if(q==1)
for(i=0;i<N-1;i++)
pf(cun[i][0],cun[i][1],cun[i][2]);
else printf("No answer.");
scanf(" %c",&p);
} while(p!='n');
}