|
回复:(lzx-shmily)求最簡單代碼
其实就是求组合数,也可以使用递归算法。下面是优化一下原来的代码
Dim showstr As String
Dim totalA As Single
Dim A(6) As Single
Private Sub 命令0_Click()
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim m As Integer
A(0) = 3.1
A(1) = 1.7
A(2) = 2
A(3) = 5.3
A(4) = 0.9
A(5) = 7.2
totalA = 10
For i = 0 To 5
For j = i + 1 To 5
For k = j + 1 To 5
For l = k + 1 To 5
For m = l + 1 To 5
CountNum i, j, k, l, m
Next
CountNum i, j, k, l, 6
Next l
CountNum i, j, k, 6, 6
Next k
CountNum i, j, 6, 6, 6
Next j
CountNum i, 6, 6, 6, 6
Next i
MsgBox Replace(showstr, " + 0", "") & "; totalA=" & Round(totalA, 2)
End Sub
Public Function CountNum(i As Integer, j As Integer, k As Integer, l As Integer, m As Integer)
If Abs(A(i) + A(j) + A(k) + A(l) + A(m) - 10) = totalA Then
showstr = showstr & "; " & CSng(A(i)) & " + " & CSng(A(j)) & " + " & CSng(A(k)) & " + " & CSng(A(l)) & " + " & CSng(A(m))
ElseIf Abs(A(i) + A(j) + A(k) + A(l) + A(m) - 10) < totalA Then
totalA = Abs(A(i) + A(j) + A(k) + A(l) + A(m) - 10)
showstr = CSng(A(i)) & " + " & CSng(A(j)) & " + " & CSng(A(k)) & " + " & CSng(A(l)) & " + " & CSng(A(m))
End If
End Function
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|