Я пытаюсь реализовать калькулятор с использованием 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