以下是C语言24点游戏的源码和流程图,供您参考:
源码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 判断输入的四个数是否合理
int is_valid(int a, int b, int c, int d) {
if (a < 1 || a > 13 || b < 1 || b > 13 || c < 1 || c > 13 || d < 1 || d > 13)
return 0;
else
return 1;
}
// 计算24点
int count24(int a, int b, int c, int d) {
int i, j, k;
double r;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (j == i) continue;
for (k = 0; k < 4; k++) {
if (k == i || k == j) continue;
r = 0;
switch (k) {
case 0:
r = a + b;
break;
case 1:
r = a - b;
break;
case 2:
r = a * b;
break;
case 3:
if (b != 0) r = a * 1.0 / b;
else continue;
break;
}
if (i == 0 && j == 1) {
if (count24(r, c, d, -1)) return 1;
if (count24(r, d, c, -1)) return 1;
} else if (i == 0 && j == 2) {
if (count24(r, c, d, -1)) return 1;
if (count24(r, d, c, -1)) return 1;
} else if (i == 0 && j == 3) {
if (count24(r, c, d, -1)) return 1;
if (count24(r, d, c, -1)) return 1;
} else if (i == 1 && j == 2) {
if (count24(a, r, d, -1)) return 1;
if (count24(a, r, c, -1)) return 1;
} else if (i == 1 && j == 3) {
if (count24(a, r, c, -1)) return 1;
if (count24(a, r, d, -1)) return 1;
} else if (i == 2 && j == 3) {
if (count24(a, b, r, -1)) return 1;
if (count24(a, b, 1.0 * d / r, -1)) return 1;
}
}
}
}
if (a + b + c + d == 24) return 1;
else return 0;
}
int main() {
int a, b, c, d;
int count = 0, correct_count = 0, error_count = 0, give_up_count = 0;
srand((unsigned)time(NULL)); // 初始化随机数种子
while (1) {
a = rand() % 13 + 1;
b = rand() % 13 + 1;
c = rand() % 13 + 1;
d = rand() % 13 + 1;
printf("请计算出%d,%d,%d,%d能否得出24点,输入0放弃:", a, b, c, d);
scanf("%d", &count);
if (count == 0) {
printf("正确答案是:");
count24(a, b, c, d);
give_up_count++;
} else if (count24(a, b, c, d) && count == 1) {
printf("恭喜你,答案正确!\n");
correct_count++;
} else if (!count24(a, b, c, d) && count == 1) {
printf("很遗憾,答案错误!\n");
error_count++;
} else if (count != 0 && count != 1) {
printf("输入有误,请重新输入!\n");
}
printf("解题次数:%d,正确次数:%d,错误次数:%d,放弃次数:%d\n",
correct_count + error_count + give_up_count, correct_count, error_count, give_up_count);
}
return 0;
}
```
流程图:
```
开始
初始化随机数种子
循环:
随机生成4个1-13的数
输出题目
输入答案
如果答案为0:
输出正确答案
放弃次数+1
如果答案为1:
如果答案正确:
输出恭喜信息
正确次数+1
如果答案错误:
输出遗憾信息
错误次数+1
如果答案不为0或1:
输出输入有误信息
输出解题次数、正确次数、错误次数、放弃次数
结束
```