c++,用扑克牌实现24点游戏
时间: 2024-06-13 21:06:54 浏览: 20
以下是使用C++实现24点纸牌游戏的示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const double eps = 1e-6;
const int N = 4;
double a[N];
bool dfs(vector<double>& nums) {
if (nums.size() == 1) {
return fabs(nums[0] - 24) < eps;
}
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
double x = nums[i], y = nums[j];
vector<double> next_nums = {x + y, x - y, y - x, x * y};
if (fabs(y) > eps) {
next_nums.push_back(x / y);
}
if (fabs(x) > eps) {
next_nums.push_back(y / x);
}
nums.erase(nums.begin() + j);
nums.erase(nums.begin() + i); for (double next_num : next_nums) {
nums.push_back(next_num);
if (dfs(nums)) {
return true;
}
nums.pop_back();
}
nums.insert(nums.begin() + i, x);
nums.insert(nums.begin() + j, y);
}
}
return false;
}
int main() {
while (cin >> a[0] >> a[1] >> a[2] >> a[3]) {
sort(a, a + N);
bool flag = false;
do {
vector<double> nums(a, a + N);
if (dfs(nums)) {
flag = true;
break;
}
} while (next_permutation(a, a + N));
if (flag) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
```