主题:24点的一个答案
输入四个数,经过+-*/得到24.本程序连3,8,3,8也可做 出8/(3-3/8).酷吧!
float f(float b,float m,float n)
{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&&m/n*n==m)
c=m/n;
else c=-1000;
return (c);}
pf(float b,float m,float n)
{
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&&m/n*n==m)
printf("%.3f/%.3f=%.3f\t",m,n,f(4,m,n));}
main ()
{float a[4],c[3],d[2],i1,i2,i3,i4,j1,j2,j3,b1,b2,b3,t;
scanf("%f,%f,%f,%f",&a[0],&a[1],&a[2],&a[3]);
for(i1=0;i1<4;i1++)
for(i2=0;i2<4;i2++)
for(i3=0;i3<4;i3++)
for(i4=0;i4<4;i4++)
{if (i1==i2||i1==i3||i1==i4||i2==i3||i2==i4||i3==i4)
continue;
for(b1=1;b1<5;b1++)
for(b2=1;b2<5;b2++)
for(b3=1;b3<5;b3++)
{c[0]=f(b1,a[i1],a[i2]);
c[1]=a[i3];
c[2]=a[i4];
for(j1=0;j1<3;j1++)
for(j2=0;j2<3;j2++)
for(j3=0;j3<3;j3++)
{if(j1==j2||j1==j3||j2==j3||c[0]<0)continue;
d[0]=f(b2,c[j1],c[j2]);
d[1]=c[j3];
if(d[0]<d[1])
{t=d[1];d[1]=d[0];d[0]=t;}
if(f(b3,d[0],d[1])==24&&d[0]>=0&&c[0]>=0)
{pf(b1,a[i1],a[i2]);
pf(b2,c[j1],c[j2]);
pf(b3,d[0],d[1]);
printf("\n");
goto end;}
}
}
}
printf("No answer to the problem.\n");end:;
}
float f(float b,float m,float n)
{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&&m/n*n==m)
c=m/n;
else c=-1000;
return (c);}
pf(float b,float m,float n)
{
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&&m/n*n==m)
printf("%.3f/%.3f=%.3f\t",m,n,f(4,m,n));}
main ()
{float a[4],c[3],d[2],i1,i2,i3,i4,j1,j2,j3,b1,b2,b3,t;
scanf("%f,%f,%f,%f",&a[0],&a[1],&a[2],&a[3]);
for(i1=0;i1<4;i1++)
for(i2=0;i2<4;i2++)
for(i3=0;i3<4;i3++)
for(i4=0;i4<4;i4++)
{if (i1==i2||i1==i3||i1==i4||i2==i3||i2==i4||i3==i4)
continue;
for(b1=1;b1<5;b1++)
for(b2=1;b2<5;b2++)
for(b3=1;b3<5;b3++)
{c[0]=f(b1,a[i1],a[i2]);
c[1]=a[i3];
c[2]=a[i4];
for(j1=0;j1<3;j1++)
for(j2=0;j2<3;j2++)
for(j3=0;j3<3;j3++)
{if(j1==j2||j1==j3||j2==j3||c[0]<0)continue;
d[0]=f(b2,c[j1],c[j2]);
d[1]=c[j3];
if(d[0]<d[1])
{t=d[1];d[1]=d[0];d[0]=t;}
if(f(b3,d[0],d[1])==24&&d[0]>=0&&c[0]>=0)
{pf(b1,a[i1],a[i2]);
pf(b2,c[j1],c[j2]);
pf(b3,d[0],d[1]);
printf("\n");
goto end;}
}
}
}
printf("No answer to the problem.\n");end:;
}