24点算法

来源:互联网 发布:java gui编程 对话框 编辑:程序博客网 时间:2024/06/08 13:17

题目描述:

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;}}}


原创粉丝点击