arrays - 如何从数组中读取两个插槽并使用递归函数将它们组合起来?
问题描述
我正在尝试使用 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
解决方案
这可能会帮助您入门:
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
推荐阅读
- spring - 没有太多信息的自定义 JPA 查询失败
- loops - 使用 Google Colabs 在循环内绘图
- python - np.copy(X) 和 np.array(X) 之间的区别
- django - 模型实例上的 Django 反向(on_delete)保护
- javascript - 为什么我必须在 JS require() 语句中使用 {}
- gtk - 如何在 Ubuntu 16.04 上安装 glib2.64
- excel - excel中的动态源文件路径
- rule-engine - Grakn 中的规则错误:“规则没有形成有效的子句,因为它包含多原子头”
- apache-kafka - Kafka 消费组描述不包括所有主题
- database - 如何在 Postgres 的多个列中获取查询结果?