# C语言实现24点游戏算法

``````#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool game24(char ch[],char flat,int data[],int num,int sum)
{
if(num > 1)//记录加减乘除符号，其中表示将除数和被除数调换位置ab ==> b/a.
ch[num-2] = flat;
if(num == 4)
{
if(sum == 24)//能够得到24就返回true
return true;
else
return false;
}
if(num == 0)//第一次进来
{
return game24(ch,'0',data,num+1,data[num]);
}
if(sum%data[num] == 0)//能够整除(因为如果有余数时，计算机只会取整数部分，得到的结果就错了)
{
if(sum != 0)//避免除以0
return game24(ch,'+',data,num+1,sum+data[num])||game24(ch,'-',data,num+1,sum-data[num])||game24(ch,'*',data,num+1,sum*data[num])||game24(ch,'/',data,num+1,sum/data[num])||game24(ch,'\',data,num+1,data[num]/sum);
else
return game24(ch,'+',data,num+1,sum+data[num])||game24(ch,'-',data,num+1,sum-data[num])||game24(ch,'*',data,num+1,sum*data[num])||game24(ch,'/',data,num+1,sum/data[num]);
}else
{
if(sum != 0)
return game24(ch,'+',data,num+1,sum+data[num])||game24(ch,'-',data,num+1,sum-data[num])||game24(ch,'*',data,num+1,sum*data[num])||game24(ch,'\',data,num+1,data[num]/sum);
else
return game24(ch,'+',data,num+1,sum+data[num])||game24(ch,'-',data,num+1,sum-data[num])||game24(ch,'*',data,num+1,sum*data[num]);
}

}

//对四个数字进行排列组合
bool sort(int data[],char ch[],int a,int b,int c,int d)
{
int num = 0,sum = 0;
int i = 0;
int j = 0;
int n = 0;
int m = 0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(i == j)
continue;
for(n=0;n<4;n++)
{
if(n == j || n == i)
continue;
for(m=0;m<4;m++)
{
if(m == n || m == j || m == i)
continue;
data[i] = a;
data[j] = b;
data[n] = c;
data[m] = d;
if(game24(ch,'0',data,num,sum))
return true;
}
}
}
}

return false;
}

int main()
{
int a = 1;
int b = 2;
int c = 8;
int d = 9;
int data[4] = {0};
char ch[3] = {0};
if(sort(data,ch,a,b,c,d))
{
printf("%d%c%d%c%d%c%dn",data[0],ch[0],data[1],ch[1],data[2],ch[2],data[3]);
}
else
printf("falsen");
}
``````

THE END

)">