穷举的,输出在立即窗口,小数位数可以自己改变,一般2-4位够了,多了意义不大,而且计算时间过长
- Dim Arr, fN&, DT#, cMin#, Result$
- Sub test()
- Dim N&
- With ThisWorkbook.Worksheets("计算")
- Arr = .[a1].CurrentRegion.Value
- DT = 2200 '目标数值
- fN = 4 '小数位数
- cMin = 0: Result = ""
- Try LBound(Arr) + 1, 0, 0, 0, ""
- If Result <> "" Then
- Debug.Print cMin
- Arr = Split(Mid(Result, 2), "|")
- For N = LBound(Arr) To UBound(Arr)
- Arr(N) = CStr(Format(Arr(N), IIf(fN > 2, "0." & String(fN - 2, "0") & "%", "0%")))
- Next N
- Debug.Print Join(Arr, vbCrLf)
- End If
- End With
- End Sub
- Function Try(ByVal curIndex&, ByVal iSum#, ByVal dSum#, ByVal bSum#, ByVal Str$)
- Dim N&, I&, D#, T#
- If curIndex = UBound(Arr) Then
- D = 1 - iSum
- dSum = dSum + Arr(curIndex, 3) * D
- If dSum = DT Then
- bSum = bSum + Arr(curIndex, 2) * D
- If cMin = 0 Or cMin > bSum Then
- cMin = bSum: Result = Str & "|" & D
- End If
- End If
- Else
- For N = 1 To 10 ^ fN Step 1
- T = dSum + Arr(curIndex, 3) * N / (10 ^ fN)
- If iSum + N / (10 ^ fN) <= 1 And T <= DT Then
- Try curIndex + 1, iSum + N / (10 ^ fN), T, bSum + Arr(curIndex, 2) * N / (10 ^ fN), Str & "|" & N / (10 ^ fN)
- Else
- Exit For
- End If
- Next N
- End If
- End Function
复制代码 代码没经过什么优化,效率一般 |