本文实例为大家分享了C++计算24点的的具体代码,供大家参考,具体内容如下
近来家庭作业里有24点的题目,为了找出所有可能的组合,就写了个简单的程序:
1. 运行程序
2. 输入4个整数,比如:3 3 7 8
3. 显示所有可能的组合
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
#include "assert.h" #include <iostream> double operate( double num1, double num2, int op) { assert (op >= 0 && op < 4); if (op == 0){ return num1 + num2; } else if (op == 1){ return num1 - num2; } else if (op == 2){ return num1 * num2; } else { return num1/num2; } } int calculate( int num1, int num2, int num3, int num4) { char operators[] = "+-*/" ; for ( int i = 0; i < 4; i ++) { for ( int j = 0; j < 4; j ++) { for ( int k = 0; k < 4; k ++) { double ret = operate(num1, num2, i); ret = operate(ret, num3, j); ret = operate(ret, num4, k); if ( abs (ret - 24) < 0.001){ printf ( "((%d %c %d) %c %d) %c %d = %f\n" , num1, operators[i], num2, operators[j], num3, operators[k], num4, ret); } ret = operate(num1, num2, i); double ret2 = operate(num3, num4, k); ret = operate(ret, ret2, j); if ( abs (ret - 24) < 0.001){ printf ( "(%d %c %d) %c (%d %c %d) = %f\n" , num1, operators[i], num2, operators[j], num3, operators[k], num4, ret); } ret = operate(num2, num3, j); ret = operate(num1, ret, i); ret = operate(ret, num4, k); if ( abs (ret - 24) < 0.001){ printf ( "(%d %c (%d %c %d)) %c %d = %f\n" , num1, operators[i], num2, operators[j], num3, operators[k], num4, ret); } ret = operate(num2, num3, j); ret = operate(ret, num4, k); ret = operate(num1, ret, i); if ( abs (ret - 24) < 0.001){ printf ( "%d %c ((%d %c %d) %c %d) = %f\n" , num1, operators[i], num2, operators[j], num3, operators[k], num4, ret); } ret = operate(num3, num4, k); ret = operate(num2, ret, j); ret = operate(num1, ret, i); if ( abs (ret - 24) < 0.001){ printf ( "%d %c (%d %c (%d %c %d)) = %f\n" , num1, operators[i], num2, operators[j], num3, operators[k], num4, ret); } } } } return 0; } int main( int argc, char * argv[]) { int nums[4] = {0, 0, 0, 0}; std::cin >> nums[0] >> nums[1] >> nums[2] >> nums[3]; for ( int i = 0; i < sizeof (nums)/ sizeof (nums[0]); i ++) { int num1 = nums[i]; int ret = num1; for ( int j = 0; j < sizeof (nums)/ sizeof (nums[0]); j ++) { if (j == i) continue ; int num2 = nums[j]; for ( int k = 0; k < sizeof (nums)/ sizeof (nums[0]); k++) { if ( k == i || k == j) continue ; int num3 = nums[k]; for ( int l = 0; l < sizeof (nums)/ sizeof (nums[0]); l ++) { if (l == i || l == j || l == k) continue ; int num4 = nums[l]; calculate(num1, num2, num3, num4); } } } } return 0; } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/cjzs1108/article/details/40628431?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task