简体   繁体   English

使用visual basic的递归/ Fibonacci

[英]Recursion/Fibonacci using visual basic

Public Class Form1

Private Function fib()
    Dim result As Integer

    If (NUD1.Value < 2) Then
        result = 1
        Return result
    Else
        result = fib(NUD1.Value - 1) + fib(NUD1.Value - 2)
        Return result

    End If

End Function


Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click

    LbFb1.Items.Add(fib())
End Sub

End Class 结束班

For some reason it only returns value a value for 0,1 and crashes if I go above 2. Any ideas ? 出于某种原因,它只返回值为0的值,如果我超过2则崩溃。任何想法?

you are not modifying NUD1.value upon each recursion the value has to be updated that is the logic of this function 你没有在每次递归时修改NUD1.value,必须更新这个函数逻辑的值

    Function fib(ByVal n)
    If n < 2 Then Return n Else Return fib(n - 1) + fib(n - 2)
    End Function

In this case if your returning "Result" it should be passed in the next recurring function but in this case you are passing NUD1.value which is incorrect 在这种情况下,如果你返回“结果”它应该在下一个循环函数中传递但在这种情况下你传递的NUD1.value不正确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM