24点游戏

游戏规则: 从扑克中每次取出4张牌。使用加减乘除,第一个能得出24者为赢。(其中,J代表11,Q代表12,K代表13,A代表1),按照要求编程解决24点游戏。
随机生成4个代表扑克牌牌面的数字字母,程序自动列出所有可能算出24的表达式,用擅长的语言(C/C++/Java或其他均可)实现程序解决问题。
源代码:

#include "pch.h"
#include"stdlib.h"
#include<time.h>
#include <iostream>
using namespace std;
int a[4] ;
char b[4] = {'+','-','*','/'};
int jisuan(int m, int n, int i) {
	if (b[i] == '+')
		return(m + n);
	if (b[i] == '-')
		return(m - n);
	if (b[i] == '*')
		return(m*n);
	if (b[i] =='/'&&n!=0)
		return(m / n);
}
int main()
{
	int a[4];
	srand(time(NULL));
	for (int i = 0; i <= 3; i++)
	{
		a[i] = rand() % 13 + 1;
	}
	cout << "a=" << a[0] << endl;
	cout << "b=" << a[1] << endl;
	cout << "c=" << a[2] << endl;
	cout << "d=" << a[3] << endl;
	int t1, t2, t3;
	for (int i = 0; i <= 3; i++)
	{
		for (int m = 0; m <= 3; m++)
		{
			if (i != m)
				for (int j = 0; j <= 3; j++)
				{
					if (m != j)
						for (int t = 0; t <= 3; t++)
						{
							if (j != t)
								for (int k = 0; k <= 3; k++)
								{
									t1 = jisuan(a[i], a[m], k);
									for (int x = 0; x <= 3; x++)
									{
										t2 = jisuan(t1, a[j], x);
										for (int y = 0; y <= 3; y++)
										{
											t3 = jisuan(t2, a[t], y);
											if (t3 == 24)
											{
												cout << "(" << "(" << "(" << a[i] << b[k] << a[m] << ")" << b[x] << a[j] << ")" << b[y] << a[t] << ")" << "=" << 24 << endl;
											}
										}
									}
								}
						}
				}
		}
	}
}

基本思路:将四个数字的运算拆分为三步,对每一步进行运算符及数字遍历求出所有结果,并将中间过程用t1,t2,t3来存储。若最终t3为24则将数字及运算符输出。
测试结果截屏:24点游戏