2012年(106)
分类: C/C++
2012-05-08 17:20:07
24点问题:4张1~10的扑克牌,通过四则运算得到24。(穷举)
程序:
#include
#include
#include
int Myoperator(float a,float b,float c,floatd);
float flagSymbol(int flag,float m,float n);
void print24result(int type,int i,int j,intk,float a,float b,float c,float d);
int time,temp=0;
void main()
{
system("title megamirurutia—24点问题 ");
inti,j,k,t,again,res,flag;
floatnum[4];
again=1;
while(again==1)
{
printf("\nPlease Enter 4 nums(1~10):\n");
i=0;
flag=0;
while(flag==0)
{
i++;
for(i=0;i<4;i++)
{
printf ("Inputnum-%d\n",++i);
i--;
scanf("%f",&num[i]);
if(num[i]<1 || num[i]>10 || num[i]!=int(num[i]))
flag++;
}
if(flag!=0)
{
printf("Error input again\n",i);
flag=0;
}
else
flag=1;
}
for(i=0;i<4;i++)
for(j=0;j<4;j++)
if(j!=i)
for(k=0;k<4;k++)
if(k!=j && k!=i)
for(t=0;t<4;t++)
if(t!=i && t!=j && t!=k)
{
res=Myoperator(num[i],num[j],num[k],num[t]);
}
if(res==0)
printf("\nNo answer\n");
else;
printf("time=%d\n\n",time);
printf("\n1: Go on\n2: Quit\n");
scanf("%d",&again);
}
}
int Myoperator(float a,float b,floatc,float d)
{
inti,j,k;
floatsum1,sum2,sum3;
for(i=0;i<4;i++)
for(j=0;j<6;j++)
for(k=0;k<6;k++)
{
if((!(i==3 && b==0)) && (!(j==3 && c==0)) &&(!(k==3 && d==0)))
{
sum1=flagSymbol(i,a,b);
sum2=flagSymbol(j,sum1,c);
sum3=flagSymbol(k,sum2,d);
if(fabs(sum3-24)<0.1)
{
temp++;
print24result(1,i,j,k,a,b,c,d);
}
}
if(k==2)
{
sum1=flagSymbol(i,a,b);
sum2=flagSymbol(j,c,d);
sum3=sum1*sum2;
if(fabs(sum3-24)<0.1)
{
temp++;
print24result(2,i,j,k,a,b,c,d);
}
}
if(k==3)
{
sum1=flagSymbol(i,a,b);
sum2=flagSymbol(j,c,d);
if(sum2!=0)
{
sum3=sum1/sum2;
if(fabs(sum3-24)<0.1)
{
temp++;
print24result(3,i,j,k,a,b,c,d);
}
}
}
}
if(temp==0)
return0;
else
return1;
}
float flagSymbol(int flag,float m,float n)
{
time++;
if(flag==0)
return(m+n);
if(flag==1)
return(m-n);
if(flag==2)
return(m*n);
if(flag==3)
if(n==0)
return30000;
else
return(m/n);
if(flag==4)
return(n-m);
if(flag==5)
if(m==0)
return30000;
else
return(n/m);
return0;
}
void print24result(int type,int i,int j,intk,float a,float b,float c,float d)
{
charsymbol[6];
symbol[0]='+';
symbol[1]='-';
symbol[2]='*';
symbol[3]='/';
symbol[4]='-';
symbol[5]='/';
if(type==1){
if(j==4|| j==5)
{
if(k==4 || k==5)
printf("%2.0f%c(%2.0f%c(%2.0f%c%2.0f))=24\n",d,symbol[k],c,symbol[j],a,symbol[i],b);
else
printf("(%2.0f%c(%2.0f%c%2.0f))%c%2.0f=24\n",c,symbol[j],a,symbol[i],b,symbol[k],d);
}
elseif (k==4 || k==5)
{
printf("%2.0f%c((%2.0f%c%2.0f)%c%2.0f)=24\n",d,symbol[k],a,symbol[i],b,symbol[j],c);
}
else
printf("((%2.0f%c%2.0f)%c%2.0f)%c%2.0f=24\n",a,symbol[i],b,symbol[j],c,symbol[k],d);
}
if(type==2 || type==3)
{
if(k==4 || k==5)
printf("(%2.0f%c%2.0f)%c(%2.0f%c%2.0f)=24\n",c,symbol[j],d,symbol[k],a,symbol[i],b);
else
printf("(%2.0f%c%2.0f)%c(%2.0f%c%2.0f)=24\n",a,symbol[i],b,symbol[k],c,symbol[j],d);
}
}