如何用c实现24点
代码如下
int chu(int p, int q) //除法运算
{
if (p%q == 0)
return p / q;
else
return 111111;
}
int fun(int i, int j, int c) //c(局部变量)选择运算符,i,j为运算数字
{
int s;
switch (c)
{
case 1: s = i + j; break;
case 2: s = i - j; break;
case 3: s = i*j; break;
case 4: s = chu(i, j); break;
}
return s;
}
void print(int c) //c(局部变量)选择输出运算符
{
if (c == 1)printf("+");
else if (c == 2)printf("-");
else if (c == 3)printf("*");
else printf("/");
}
int main()
{
int w;
int f[4];//四个1-13的数
int i, j, m, n;
int a, b, c;//符号
int d1, d2, d3; //每步的结果
srand(time(NULL)); //随机生成四个数字(四张扑克牌)
for (int w = 0; w<4; w++)
{
f[w] = rand() % 13 + 1; //生成随机数范围在1~13
}
for (w = 0; w<4; w++)
{
printf("%d ", f[w]);
}
printf("\n");
for (i = 0; i<4; i++)
for (j = 0; j<4; j++)
if (j != i)
for (m = 0; m<4; m++)
if (m != i&&m != j)
for (n = 0; n<4; n++)
if (n != i&&n != j&&n != m) //四个数字的位置不可重复且多重可能置换位置运算
for (a = 1; a<5; a++)
for (b = 1; b<5; b++)
for (c = 1; c<5; c++) //选择四个数字中间的三个运算符,皆有四种可能
{ //避免了对括号的思考,转化为二元运算
d1 = fun(f[i], f[j], a);
d2 = fun(d1, f[m], b); //用前两个数字的运算结果代替
d3 = fun(d2, f[n], c); //同理,两两运算,递归过程
if (d3 == 24)
{
printf("%d", f[i]);
print(a);
printf("%d", f[j]);
print(b);
printf("%d", f[m]);
print(c);
printf("%d=24\n", f[n]);
}
}
system("pause");
return 0;
}