|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
在ChatGPT给的代码上优化了一下,运行时间从17秒减少到0.01秒。就是在循环里加入s1,s2,s3随时判断,当s1或S2或s3大于最小值里,后续的循环就没有必要进行了。
- Sub minExpression()
- Dim a As Integer, b As Integer, c As Integer, d As Integer
- Dim s1&, s2&, s3&, s&
- Dim minVal As Double, val As Double
- Dim minA As Integer, minB As Integer, minC As Integer, minD As Integer
- tm = Timer
- minVal = 10000 ' 初始化为最大值
-
- For a = 1 To 100
- For b = 1 To 100
- s1 = Abs(11 * a - 13 * b)
- If s1 < minVal Then
- For c = 1 To 100
- s2 = Abs(11 * a - 12 * c)
- s3 = Abs(13 * b - 12 * c)
- If s2 < minVal And s3 < minVal Then
- s = s1 + s2 + s3
- For d = 1 To 100
- val = s + Abs(11 * a - 26 * d) + Abs(13 * b - 26 * d) + Abs(12 * c - 26 * d)
- If val < minVal Then ' 找到了更小的值
- minVal = val
- minA = a
- minB = b
- minC = c
- minD = d
- End If
- Next d
- End If
- Next c
- End If
- Next b
- Next a
-
- Debug.Print "最小值:" & minVal
- Debug.Print "a: " & minA
- Debug.Print "b: " & minB
- Debug.Print "c: " & minC
- Debug.Print "d: " & minD
- Debug.Print "运行时间:" & Timer - tm & "s"
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|