Dim i As Integer
For i = 1 To 4
Cells(2, i + 1).Value = Int(Rnd() * 13) + 1
Next
Range(Cells(2, 7), Cells(2, 8).End(xlDown)).ClearContents
End Sub
第一段大概是随机输出四个数字?
Function Calc(ByVal x1 As Single, ByVal x2 As Single, ByVal calctype As Integer, ByRef Result As Single, ByRef expr As String) As Boolean
Select Case calctype
Case 1
Result = x1 + x2
expr = Str(x1) & "+" & Str(x2) & "=" & Str(Result)
Case 2
Result = x1 * x2
expr = Str(x1) & "*" & Str(x2) & "=" & Str(Result)
Case 3
Result = x1 - x2
expr = Str(x1) & "-" & Str(x2) & "=" & Str(Result)
Case 4
Result = x2 - x1
expr = Str(x2) & "-" & Str(x1) & "=" & Str(Result)
Case 5
If x2 <> 0 Then Result = x1 / x2
expr = Str(x1) & "/" & Str(x2) & "=" & Str(Result)
Case 6
If x1 <> 0 Then Result = x2 / x1
expr = Str(x2) & "/" & Str(x1) & "=" & Str(Result)
End Select
End Function
第二段是录入加减乘除算法?
Function arrange(ByVal x1 As Integer, ByVal x2 As Integer, ByVal x3 As Integer, ByVal x4 As Integer, ByVal arrangetype As Integer) As Variant
Select Case arrangetype
Case 1
arrange = Array(x1, x2, x3, x4)
Case 2
arrange = Array(x1, x2, x4, x3)
Case 3
arrange = Array(x1, x3, x2, x4)
Case 4
arrange = Array(x1, x3, x4, x2)
Case 5
arrange = Array(x1, x4, x2, x3)
Case 6
arrange = Array(x1, x4, x3, x2)
Case 7
arrange = Array(x2, x1, x3, x4)
Case 8
arrange = Array(x2, x1, x4, x3)
Case 9
arrange = Array(x2, x3, x1, x4)
Case 10
arrange = Array(x2, x3, x4, x1)
Case 11
arrange = Array(x2, x4, x1, x3)
Case 12
arrange = Array(x2, x4, x3, x1)
Case 13
arrange = Array(x3, x1, x2, x4)
Case 14
arrange = Array(x3, x1, x4, x2)
Case 15
arrange = Array(x3, x2, x1, x4)
Case 16
arrange = Array(x3, x2, x4, x1)
Case 17
arrange = Array(x3, x4, x1, x2)
Case 18
arrange = Array(x3, x4, x2, x1)
Case 19
arrange = Array(x4, x1, x2, x3)
Case 20
arrange = Array(x4, x1, x3, x2)
Case 21
arrange = Array(x4, x2, x1, x3)
Case 22
arrange = Array(x4, x2, x3, x1)
Case 23
arrange = Array(x4, x3, x1, x2)
Case 24
arrange = Array(x4, x3, x2, x1)
End Select
End Function
第三段是用穷举法列出四个数字的排列顺序
Sub Auto_计算()
Application.ScreenUpdating = False
Range(Cells(2, 7), Cells(2, 8).End(xlDown)).ClearContents
Dim a, b, c, d, calcorder, calc1, calc2, calc3, z As Integer
Dim result1 As Single, result2 As Single, result3 As Single
Dim expr1 As String, expr2 As String, expr3 As String
Dim n
a = Cells(2, 2).Value
b = Cells(2, 3).Value
c = Cells(2, 4).Value
d = Cells(2, 5).Value
z = 0
For calcorder = 1 To 24
n = arrange(a, b, c, d, calcorder)
For calc1 = 1 To 6
Calc n(0), n(1), calc1, result1, expr1
For calc2 = 1 To 6
Calc result1, n(2), calc2, result2, expr2
For calc3 = 1 To 6
Calc result2, n(3), calc3, result3, expr3
If Round(result3, 2) = 24 Then
z = z + 1
Cells(1 + z, 7).FormulaR1C1 = "第" & z & "种解:"
Cells(1 + z, 8).FormulaR1C1 = Trim(expr1) & vbCrLf & Trim(expr2) & vbCrLf & Trim(expr3)
End If
Next
Next
Next
Next
If z = 0 Then
MsgBox ("此组数字无解!")
End If
Application.ScreenUpdating = True
End Sub
核心算法,有点晕,看不明白,求解释