简体   繁体   中英

Function with array returning 0 Visual Basic

I'm quite new at using arrays and functions in Visual Basic and I cannot seem to figure this out. My problem is that whenever I call the function Fibo it returns 0 no matter the value of n I give it. I'm sure the error is pretty basic.

Any pointer would be really appreciated!

Public Function fibo(n As Integer) As Integer

    Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci

    arrayFib(0) = 0 'idem
    arrayFib(1) = 1 'declare start value

    Dim i As Integer = 2 'start position

    While i <= n
        arrayFib(i) = arrayFib(i - 1) + arrayFib(i - 2)
        i = 1 + i

    Return arrayFib(i)
Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci

We can sort of guess where that +1 came from. You added it because your original code crashed with an IndexOutOfRangeException. Caused by you returning arrayFib(i), i was incremented to be larger than n, its value is n+1 after the loop. And thus returns the value of an element that was never assigned. You didn't fix it correctly :)

Fix the array declaration back the way it was and return arrayFib(n) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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