首页 > 解决方案 > 如何从数组中读取两个插槽并使用递归函数将它们组合起来?

问题描述

我正在尝试使用 VBA 实现一个计算器。我在使用递归计算结果时遇到了麻烦。

我试过实现这个功能。我总是最终得到结果为零。

主意:

比如要计算2+3+4+5

该函数将在每一步中递归地读取和组合两个元素。例如,在第 2 步,从第一个位置开始,数组的前两个插槽给您“2”和“+”,因此您知道需要从位置 3 开始将 2 添加到数组的其余部分。最后,数组的结果将是 5(来自步骤 5)+ 4(来自步骤 4)+ 3(来自步骤 3)+ 2(来自步骤 2)= 14。

请在下面找到代码。我已经尝试实现它,但我收到类型不匹配错误。“显示”是一个字符串,用于记住计算器的当前显示。

Dim Memory(1 To 100) As String

' The current position used by the calculator inside the memory array
Dim CurrentPos As Integer

' This function is a recursive function for calculating the result of the expression
' stored in the Memory array, starting at the position Pos.
'
' Note that the return value is a Long number. When you calculate the result you need
' to convert the numbers (as text) in the memory to long numbers using CLng().
Function CalcTotal(ByVal Pos As Integer) As Long
    '
    ' Task 4: Calculating the Result Using Recursion
    '

    ' Case 1: if Pos is bigger than what you have in the Memory array

        ' Nothing is available

    ' Case 2: if Pos is exactly at the end of the Memory array

        ' Return the number in the position

    ' Case 3: Memory(Pos) is a number and Memory(Pos + 1) is an operator

        ' Return the number in the current position together with the rest of the Memory array
    If Pos > CurrentPos Then ' Case 1: Nothing left to read
        Display = "0"
        'return 0 as the result because there is nothing to do...
    ElseIf Pos = CurrentPos Then ' Case 2: There is only a number left
        Display = CLng(Memory(Pos))
        'return the number in the current position...
    Else ' Case 3: Read the next two slots of the array and combine with the rest of the array
        Display = CLng(Memory(Pos)) + CLng(Memory(Pos + 1))
        CalcTotal (Pos + 2)
    End If
End Function

标签: arraysexcelvba

解决方案


这可能会帮助您入门:

Public MyInputs As Variant

Sub Test()
    MyInputs = Array("2", "+", "3", "+", "4", "+", "5")
    Debug.Print Application.Evaluate(CalcTotal(UBound(MyInputs)))  '~~> prints 14
End Sub

Function CalcTotal(n As Integer) As String
    If n = 0 Then
        CalcTotal = MyInputs(n)
    Else
        CalcTotal = MyInputs(n) & (CalcTotal(n - 1))
    End If
End Function

笔记:

  • CalcTotal将返回一个字符串,例如5+4+3+2
  • Application.Evaluate将该字符串解析为计算并打印14

推荐阅读