24点算法

题目描述:

1-9 9个数字中随机选出4个,使用+、-、*、/4种运算符,使它们的结果为24。

主要思想:穷举法

从1-9中选4个数共有9*8*7*6/4! = 126种选法,然后从126种选法中选出使用+、-、*、/4种运算符
结果为24的数字输出。代码如下:

#include<iostream>
using namespace std;

const int N = 4;

void tweFourColck(int a[]);						//穷举24点
float calc(float a, float b, char oper);		//计算
void combination(int a[], int n, int k);		//组合

int main()
{
	int a[N];
	combination(a, 9, N);
	system("pause");
	return 0;
}


float calc(float a, float b, char oper)
{
	switch (oper)
	{
	case '+':
		return a + b;
	case '-':
		return a - b;
	case '*':
		return a * b;
	case '/':
		return a / b;
	}
}

void combination(int a[], int n, int k)
{
	if (k == 0)
	{
		tweFourColck(a);
		return;
	}
	for (int i = n; i >= k; i--)
	{
		a[k - 1] = i;
		combination(a, i - 1, k - 1);
	}
}

void tweFourColck(int a[])
{
	char oper[] = { '+', '-', '*', '/' };
	for(int i = 0; i < 4; i++)
		for (int j = 0; j < 4; j++)
			for (int k = 0; k < 4; k++)
				{
					float s = calc(a[0], a[1], oper[i]);
					s = calc(s, a[2], oper[j]);
					s = calc(s, a[3], oper[k]);
					if (s == 24)
					{
						cout << a[0] << oper[i] << a[1] << oper[j];
						cout << a[2] << oper[k] << a[3] << endl;
					}
				}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值