one day
24点游戏的代码,程序内按顺序计算,没有符号的优先级计算
#include#include #include #include time_t tBegin; time_t tTemp; int dp=0; int ttime=300; void outNum(int flag){ switch(flag){ case 1: printf("A\n"); break; case 13: printf("K\n"); break; case 12: printf("Q\n"); break; case 11: printf("J\n"); break; case 10: printf("10\n"); break; default: printf("%d\n",flag); } } int checkIn(int num[4],char c[3]){ int ans = 0; ans += num[0]; for(int i = 0; i < 3; i++){ switch(c[i]){ case '+': ans += num[1+i]; break; case '-': ans -= num[1+i]; break; case '*': ans *= num[1+i]; break; case '/': ans /= num[1+i]; break; } } return ans; } bool checkOut(int num[4],int chioce){ int dp1; if(chioce==1||chioce==11){ dp1=2; }else{ dp1=4; } char c[4] = {'+','-','*','/'}; int flag[4]; char cflag[3]; for(int i1 = 0; i1 < 4; i1++){ for(int j1 = 0; j1 < dp1; j1++){ for(int i2 = 0; i2 < 4; i2++){ if(i1==i2) continue; for(int j2 = 0; j2 < dp1; j2++){ for(int i3 = 0; i3 < 4; i3++){ if(i1==i3||i2==i3) continue; for(int j3 = 0; j3 < dp1; j3++){ for(int i4 = 0; i4 < 4; i4++){ if(i1==i4||i2==i4||i3==i4) continue; flag[0] = num[i1]; flag[1] = num[i2]; flag[2] = num[i3]; flag[3] = num[i4]; cflag[0] = c[j1]; cflag[1] = c[j2]; cflag[2] = c[j3]; if(checkIn(flag,cflag)==24){ if(dp==1){ for(int i = 0; i < 7; i++){ if(i%2==0){ printf("%d",flag[i/2]); }else{ printf("%c",cflag[i/2]); } } printf("\n"); } return true; } } } } } } } } return false; } int main() { int num[4]; srand(time(0)); int chioce; printf("\n **欢迎来到24点游戏!**\n\n"); do{ printf("**请选择你想选择的游戏难度\n\n**输入1 选择简单模式(限时300s内)\n**输入11 选择进阶简单模式(限时30s内)\n**输入2 选择困难模式(限时300s内)\n**输入22 选择魔鬼模式(限时30s内)\n\n请输入你的选择:"); scanf("%d",&chioce); do{ int i = 0; while(i<4){ num[i] = rand()%52+1; i++; } for(int i = 0; i < 4; i++) num[i] = num[i]%13+1; }while(!checkOut(num,chioce)); printf("\n扑克牌 1: "); outNum(num[0]); printf("扑克牌 2: "); outNum(num[1]); printf("扑克牌 3: "); outNum(num[2]); printf("扑克牌 4: "); outNum(num[3]); printf("请选择数字的号码进行计算(例如 1*2+3-4)\n"); tBegin = time(NULL); int numIn[4]; char c[3]; for(int i = 0; i < 7; i++){ if(i%2==0){ scanf("%d",&numIn[i/2]); }else{ c[i/2] = getchar(); } } for(int i = 0; i < 4; i++) numIn[i] = num[numIn[i]-1]; tTemp = time(NULL); int flag; flag = checkIn(numIn,c); if(flag==24){ if(chioce==1||chioce==2){ ttime=30; } if(tTemp - tBegin >ttime){ printf("**对不起您虽然答案正确,但是超出了游戏时间。**\n"); } else printf("\n****恭喜你,你的答案正确。*****\n"); } else{ printf("\n\n****很抱歉,你的答案错误!****\n"); printf(" 以下为所有正确答案:\n"); dp=1; do{ }while(!checkOut(num,2)); } printf("\n\n输入1选择继续游戏,输入3选择退出游戏!"); scanf("%d",&chioce); dp=0; ttime=30; }while(chioce==1||chioce==2||chioce==11||chioce==22); return 0; }