|
- Sub MakeUpNumbers()
- Dim TargetNumber As Double
- Dim Numbers As Variant
- Dim OutputRow As Integer
- Dim RequiredCombinations As Integer
- ' 设置目标数值
- TargetNumber = 6000
- ' 初始化数字数组
- Numbers = Array(1354.5, 1486, 1643.7, 1821, 2053, 3255, 3679, 3832)
- ' 计算所需的组合数量
- RequiredCombinations = WorksheetFunction.RoundUp((1354.5 + 1486 + 1643.7 + 1821 + 2053 + 3255 + 3679 + 3832) / 6000, 0)
- ' 初始化输出行
- OutputRow = 1
- ' 调用函数生成数字组合
- FindNumbers TargetNumber, Numbers, OutputRow, RequiredCombinations
- End Sub
- Sub FindNumbers(Target As Double, Numbers As Variant, OutputRow As Integer, RequiredCombinations As Integer)
- Dim i As Integer, j As Integer, k As Integer
- Dim totalNumbers As Integer
- Dim totalCombinations As Integer
- Dim sum As Double
- Dim combination As String
- Dim count As Integer
- Dim usedNumbers As String
- Dim closestSum As Double
- Dim closestCombination As String
- Dim closestDiff As Double
- Dim foundCombinations As Integer
- closestSum = 0
- closestCombination = ""
- closestDiff = Target
- foundCombinations = 0
- totalNumbers = UBound(Numbers) - LBound(Numbers) + 1
- totalCombinations = 2 ^ totalNumbers
- For i = 1 To totalCombinations - 1
- sum = 0
- combination = ""
- count = 0
- usedNumbers = ""
- For j = 0 To totalNumbers - 1
- If ((i And (2 ^ j)) <> 0) Then
- If InStr(usedNumbers, CStr(Numbers(LBound(Numbers) + j))) = 0 Then
- sum = sum + Numbers(LBound(Numbers) + j)
- combination = combination & Numbers(LBound(Numbers) + j) & "+"
- count = count + 1
- usedNumbers = usedNumbers & CStr(Numbers(LBound(Numbers) + j)) & ","
- End If
- End If
- Next j
- If count >= 2 And sum <= Target Then
- combination = Left(combination, Len(combination) - 1) ' 移除最后一个加号
- If Abs(Target - sum) <= closestDiff Then
- closestSum = sum
- closestCombination = combination
- closestDiff = Abs(Target - sum)
- If Abs(Target - sum) < closestDiff Then
- foundCombinations = 1
- ElseIf Abs(Target - sum) = closestDiff Then
- foundCombinations = foundCombinations + 1
- End If
- Worksheets("Sheet1").Cells(OutputRow, 3).Value = closestCombination
- OutputRow = OutputRow + 1
- End If
- End If
- If foundCombinations >= RequiredCombinations Then
- Exit For
- End If
- Next i
- If foundCombinations = 0 Then
- MsgBox "未找到符合条件的数字组合。"
- Else
- MsgBox "找到 " & foundCombinations & " 个组合,组合已成功写入C列"
- End If
- End Sub
复制代码 用GPT生成的代码,没用递归,供参考吧
|
|