题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include <iostream> #include <vector> #include <algorithm> using namespace std; //存储两个数字运算后的结果 double result(double a, double b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } return 0; } int main() { vector<double> vec(4, 0); while (cin >> vec[0] >> vec[1] >> vec[2] >> vec[3]) { sort(vec.begin(), vec.end()); vector<char> vec_op = {'+', '-', '*', '/'}; int flag; do { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { for (int k = 0; k < 4; ++k) { double num_1 = result(vec[0], vec[1], vec_op[i]); double num_2 = result(num_1, vec[2], vec_op[j]); double num_3 = result(num_2, vec[3], vec_op[k]); if (num_3 == 24) { cout << "true" << endl; goto end; } } } } }while(next_permutation(vec.begin(),vec.end())); cout << "false" << endl; } end: return 0; }#23届找工作求助阵地##我的实习求职记录##14天打卡计划##零基础学习C++##春招#