|
本帖最后由 香川群子 于 2014-3-21 16:55 编辑
我的通用递归计算代码:
理论上可以无限制的n个数进行反复加减乘除的四则混合运算。
但如果n值很大,计算结果越来越多就会死机。
所以实际使用时,请选择2-5个数进行递归计算。
计算目标值也不限制=24,可以输入任意数值(含小数、但不得为负数)- Dim crr(65535, 1), b, cnt&
- Sub dg_Calc() 'by kagawa
- Dim i&, n&, tms#
- tms = Timer
-
- n = [a1].End(4).Row - 1
- ReDim arr(1 To n, 1 To 2)
- For i = 1 To n
- arr(i, 1) = Cells(i + 1, 1)
- arr(i, 2) = Cells(i + 1, 1)
- Next
- b = [b2]
-
- cnt = 0: Call zhjs(arr, n)
-
- [d1].CurrentRegion.Offset(1) = ""
- If cnt Then [d2].Resize(cnt, 2) = crr
- MsgBox Format(Timer - tms, "0.000s ") & cnt
- End Sub
- Sub zhjs(arr(), n&)
- Dim i&, j&, k&, l&, f&
- ReDim brr(1 To n - 1, 1 To 2)
- For i = 1 To n - 1
- For j = i + 1 To n
- If n > 2 Then
- l = 0
- For k = 1 To n
- If k <> i And k <> j Then
- l = l + 1
- brr(l, 1) = arr(k, 1)
- brr(l, 2) = arr(k, 2)
- End If
- Next
- End If
-
- For f = 1 To 5
-
- If f = 4 And arr(i, 1) = 0 Then
-
- ElseIf f = 5 And arr(j, 1) = 0 Then
-
- Else
- brr(n - 1, 1) = js(arr(i, 1), arr(j, 1), f)
- brr(n - 1, 2) = jg(arr(i, 2), arr(j, 2), f)
- If n = 2 Then
- If Round(brr(n - 1, 1), 12) = b Then
- crr(cnt, 0) = brr(n - 1, 2)
- crr(cnt, 1) = jg(Round(arr(i, 1), 3), Round(arr(j, 1), 3), f)
- cnt = cnt + 1
- End If
- Else
- Call zhjs(brr, n - 1)
- End If
- End If
- Next
- Next
- Next
- End Sub
- Function js(n1, n2, f)
- Select Case f
- Case 1
- js = n1 + n2
- Case 2
- If n1 > n2 Then js = n1 - n2 Else js = n2 - n1
- Case 3
- js = n1 * n2
- Case 4
- If n1 = 0 Then js = "!0" Else js = n2 / n1
- Case 5
- If n2 = 0 Then js = "!0" Else js = n1 / n2
- End Select
- End Function
- Function jg(n1, n2, f)
- Select Case f
- Case 1
- jg = "(" & n1 & "+" & n2 & ")"
- Case 2
- jg = "(" & n2 & "-" & n1 & ")"
- Case 3
- jg = "(" & n1 & "*" & n2 & ")"
- Case 4
- If n1 = 0 Then jg = "/Zero" Else jg = "(" & n2 & "/" & n1 & ")"
- Case 5
- If n2 = 0 Then jg = "/Zero" Else jg = "(" & n1 & "/" & n2 & ")"
- End Select
- End Function
复制代码 |
评分
-
1
查看全部评分
-
|