时间:2020-12-05 13:08:36 | 栏目:C代码 | 点击:次
本文实例为大家分享了C语言实现24点游戏的具体代码,供大家参考,具体内容如下
参考文章:C语言实现经典24点算法
将算法实现改成C语言,并可在linux服务器上运行。同时修改为可显示所有结果。
注:如果传参重复,如4,4,7,7这样,会回显重复结果,暂无法清除。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> const double PRECISION = 1E-6; #define COUNT 4 const int RESULT = 24; #define STRLEN 50 double number[COUNT] = {0}; //这里一定要用double, char expression[COUNT][STRLEN] = {0}; //保存表达式 #define TRUE 1 #define FALSE 0 int cnt = 0; void Test(int n) { int i = 0; int j = 0; int len = 0; //递归结束 if(1 == n){ if(number[0] == RESULT) { // 避免输出前后括号 for (i = 1; i < strlen(expression[0]) - 1; i++) { printf("%c", expression[0][i]); } printf("\n"); cnt++; return; } else return; } //递归过程 for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ double a,b; char expa[STRLEN] = {0}; char expb[STRLEN] = {0}; a=number[i]; b=number[j]; // 删除number[j]元素,用number[n-1]填补 number[j]=number[n-1]; strcpy(expa, expression[i]); strcpy(expb, expression[j]); // 删除expression[j]元素,用expression[n-1]填补 strcpy(expression[j], expression[n-1]); // 加法 len= strlen(expression[i]); snprintf(expression[i], STRLEN, "(%s+%s)", expa, expb); number[i]=a+b; Test(n-1); //减号有两种情况,a-b与b-a len= strlen(expression[i]); snprintf(expression[i], STRLEN, "(%s-%s)", expa, expb); number[i]=a-b; Test(n-1); if(a != b) { len= strlen(expression[i]); snprintf(expression[i], STRLEN, "(%s-%s)", expb, expa); number[i]=b-a; Test(n-1); } // 乘法 len= strlen(expression[i]); snprintf(expression[i], STRLEN, "(%s*%s)", expa, expb); number[i]=a*b; Test(n-1); //除法也有两种情况,a/b与b/a if(b!=0){ len= strlen(expression[i]); snprintf(expression[i], STRLEN, "(%s/%s)", expa, expb); number[i]=a/b; Test(n-1); } if((a!=0) && (a != b)){ len= strlen(expression[i]); snprintf(expression[i], STRLEN, "(%s/%s)", expb, expa); number[i]=b/a; Test(n-1); } //恢复数组 number[i]=a; number[j]=b; strcpy(expression[i], expa); strcpy(expression[j], expb); } } return; } int main(int argc, char **argv) { int i = 0; if(5 != argc) { printf("arg err\n"); return 0; } for(i=0;i<COUNT;i++) { char buffer[20]; number[i] = atoi(argv[i + 1]); strcpy(expression[i], argv[i + 1]); } Test(COUNT); if(0 != cnt) { printf("Total[%d], Success\n", cnt); } else { printf("Fail\n"); } return 0; }
运行结果如下:
andy@ubuntu14:~/work$ ./test 5 6 7 8 ((5+7)-8)*6 (5+7)*(8-6) 8/((7-5)/6) (6/(7-5))*8 6/((7-5)/8) (8/(7-5))*6 (6*8)/(7-5) ((5-8)+7)*6 (7-(8-5))*6 (5+7)*(8-6) (6*8)/(7-5) (5+(7-8))*6 (5-(8-7))*6 Total[13], Success andy@ubuntu14:~/work$ ./test 7 7 7 7 Fail