#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int a[4]; // 数组a[]用于存放随机产生的四个操作数
char ope[4] = {'+','-','*','/'}; // 数组ope[]用于存放四类运算符
// 通过num()函数生成四个1-13的随机数
void num()
{
int i;
srand(time(NULL));
for(i=0; i<4; i++)
{
a[i] = rand()%13+1;
}
for(i=0; i<4; i++)
{
printf("第%d张牌:%d\n", i+1, a[i]);
}
}
// 通过cal()函数对两个操作数进行计算
int cal(int x, int y, char ope)
{
int z;
if(ope=='+')
z = x+y;
else if(ope=='-')
z = x-y;
else if(ope=='*')
z = x*y;
else if(ope=='/')
z = x/y;
return z;
}
// 通过express_1()函数计算表达式((A_B)_C)_D
int express_1(int i, int j, int k, int t, char ope1, char ope2, char ope3)
{
int x1, x2, x3;
x1 = cal(i, j, ope1);
x2 = cal(x1, k, ope2);
x3 = cal(x2, t, ope3);
return x3;
}
// 通过express_2()函数计算表达式(A_(B_C))_D
int express_2(int i, int j, int k, int t, char ope1, char ope2, char ope3)
{
int x1, x2, x3;
x1 = cal(j, k, ope2);
x2 = cal(i, x1, ope1);
x3 = cal(x2, t, ope3);
return x3;
}
// 通过express_3()函数计算表达式A_((B_C)_D)
int express_3(int i, int j, int k, int t, char ope1, char ope2, char ope3)
{
int x1, x2, x3;
x1 = cal(j, k, ope2);
x2 = cal(x1, t, ope3);
x3 = cal(i, x2, ope1);
return x3;
}
// 通过express_4()函数计算表达式A_(B_(C_D))
int express_4(int i, int j, int k, int t, char ope1, char ope2, char ope3)
{
int x1, x2, x3;
x1 = cal(k, t, ope3);
x2 = cal(j, x1, ope2);
x3 = cal(i, x2, ope1);
return x3;
}
// 通过express_5()函数计算表达式(A_B)_(C_D)
int express_5(int i, int j, int k, int t, char ope1, char ope2, char ope3)
{
int x1, x2, x3;
x1 = cal(i, j, ope1);
x2 = cal(k, t, ope3);
x3 = cal(x1, x2, ope2);
return x3;
}
int main()
{
printf("#**************************************#\n");
printf("# #\n");
printf("# 欢迎来到 #\n");
printf("# #\n");
printf("# 24点小游戏 #\n");
printf("# #\n");
printf("#**************************************#\n");
printf("请按任意键开始游戏:\n");
getchar();
num();
int i, j, k, t;
i = a[0];
j = a[1];
k = a[2];
t = a[3];
int x, y, z;
char p, q, r;
printf("\n");
printf("所有能够出现24点的表达式有:\n");
/* 通过三个for循环的嵌套,穷举出四个随机数所能组成的所有表达式;
通过与最里层for循环嵌套的五个if判断输出所有能够得到24点的表达式。*/
for(x=0; x<4; x++)
{
p = ope[x];
for(y=0; y<4; y++)
{
q = ope[y];
for(z=0; z<4; z++)
{
r = ope[z];
if(express_1(i, j, k, t, p, q, r)==24)
printf("((%d %c %d) %c %d) %c %d = 24\n", i, p, j, q, k, r, t);
if(express_2(i, j, k, t, p, q, r)==24)
printf("(%d %c (%d %c %d)) %c %d = 24\n", i, p, j, q, k, r, t);
if(express_3(i, j, k, t, p, q, r)==24)
printf("%d %c ((%d %c %d) %c %d) = 24\n", i, p, j, q, k, r, t);
if(express_4(i, j, k, t, p, q, r)==24)
printf("%d %c (%d %c (%d %c %d)) = 24\n", i, p, j, q, k, r, t);
if(express_5(i, j, k, t, p, q, r)==24)
printf("(%d %c %d) %c (%d %c %d) = 24\n", i, p, j, q, k, r, t);
}
}
}
}
![](https://img-blog.csdnimg.cn/direct/13e8611d18cd45c2b1eacff215501dc6.png)
![](https://img-blog.csdnimg.cn/direct/9031f3f2e7c74948be415aad009d809a.png)