Как мне прочитать два слота из массива и объединить их с помощью рекурсивной функции? - PullRequest
0 голосов
/ 18 апреля 2019

Я пытаюсь реализовать калькулятор с использованием VBA. У меня проблема с вычислением результата с использованием рекурсии.

Я пытался реализовать функцию. Я всегда получаю результат равным нулю.

Идея:

Например, 2 + 3 + 4 + 5 должно быть рассчитано

Функция будет рекурсивно читать и объединять два элемента с каждым шагом. Например, на шаге 2 из первой позиции первые два слота массива дают вам «2» и «+», так что вы знаете, что вам нужно добавить 2 к остальной части массива, начиная с позиции 3. Наконец, результат массива будет 5 (из шага 5) + 4 (из шага 4) + 3 (из шага 3) + 2 (из шага 2) = 14.

Пожалуйста, найдите код ниже. Я пытался реализовать его, но я получаю ошибку несоответствия типов. «Display» - это строка для запоминания текущего отображения калькулятора.

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

Ответы [ 2 ]

1 голос
/ 18 апреля 2019

Это может помочь вам начать:

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
0 голосов
/ 18 апреля 2019

Проблема в коде состоит в том, что вы возвращаете строку «0», для функции, которая возвращает LONG, исправление заменяет «0» (строку) на 0 (длинная).

' 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" WRONG THATS A STRING
          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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...