24点完整源程序 by hujian_198(Jack)
//Copyright by hujian_198(Jack)//Date: 2007.8.8
//尚未消除重复出现的情况
//24点完整源代码
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#define N 4
float num[N];
float math_two(float x,float y,char ch)
{
switch(ch)
{
case '+':
return (x+y);
break;
case '-':
return (x-y);
break;
case '*':
return (x*y);
break;
case '/':
if(0==y)
return -10000.0;
return (x/y);
break;
default:
break;
}
return -10000.0;
}
int math_four(float a,float b,float c,float d,char ch[])
{
int i,j,k,count=0;
float m,s,p,q,r,h,t,u,v,w,x,y,z;
for(i=0;i<N;++i)
{
m=math_two(a,b,ch[i]);
for(j=0;j<N;++j)
{
s=math_two(m,c,ch[j]);
h=math_two(b,c,ch[j]);
for(k=0;k<N;++k)
{
p=math_two(s,d,ch[k]);
if((fabs(p-24))<0.001)
{
++count;
printf("((%1.0f %c %1.0f) %c %1.0f) %c %1.0f=24\n",a,ch[i],b,ch[j],c,ch[k],d);
getch();
}
q=math_two(c,d,ch[k]);
r=math_two(m,q,ch[j]);
if((fabs(r-24))<0.001)
{
++count;
printf("(%1.0f %c %1.0f) %c (%1.0f %c %1.0f)=24\n",a,ch[i],b,ch[j],c,ch[k],d);
getch();
}
t=math_two(a,h,ch[i]);
u=math_two(t,d,ch[k]);
if((fabs(u-24))<0.001)
{
++count;
printf("(%1.0f %c (%1.0f %c %1.0f)) %c %1.0f=24\n",a,ch[i],b,ch[j],c,ch[k],d);
getch();
}
v=math_two(c,d,ch[k]);
w=math_two(b,v,ch[j]);
x=math_two(a,w,ch[i]);
if((fabs(x-24))<0.001)
{
++count;
printf("%1.0f %c (%1.0f %c (%1.0f %c %1.0f))=24\n",a,ch[i],b,ch[j],c,ch[k],d);
getch();
}
y=math_two(h,d,ch[k]);
z=math_two(a,y,ch[i]);
if((fabs(z-24))<0.001)
{
++count;
printf("%1.0f %c ((%1.0f %c %1.0f) %c %1.0f)=24\n",a,ch[i],b,ch[j],c,ch[k],d);
getch();
}
}
}
}
if(0==count)
return 0;
return count;
}
void input(void)
{
int i;
printf("\t\t\t\t24 Dots Game\n\n");
printf("Please input four integers!\n");
for(i=0;i<N;++i)
{
printf("integer %d is:",i+1);
scanf("%f",&num[i]);
}
}
void main(void)
{
int i,j,k;
int count=0,sum=0;
char sig[]={'+','-','*','/'};
input();
for(i=0;i<N;++i)
{
for(j=0;j<N;++j)
{
if(j==i)
continue;
for(k=0;k<N;++k)
{
if(k==i || k==j)
continue;
count=math_four(num[i],num[j],num[k],num[6-i-j-k],sig);
sum+=count;
}
}
}
printf("There is total %d ways.\n",sum);
}