我正在尝试实现线性搜索,但每当我转到linearSearch()
子例程时,我都会收到错误:
索引超出了数组的范围
发出此错误的行是包含If list(a) = numberToFind Then
的行。我该如何解决这个问题?
Module Module1
Sub Main()
Dim list(99) As Integer
Dim x As Integer = 0
Dim answer As Integer
Console.Write("Enter a value, type 9999 to stop.")
answer = Console.ReadLine()
For i = 0 To list.Length
If answer = 9999 Then
linearSearch(list)
Else
list(i) = answer
Console.Write("Enter another")
answer = Console.ReadLine
End If
Next
End Sub
Sub linearSearch(ByVal list)
Dim numberToFind, comparisonNo As Integer
comparisonNo = 0
Console.Write("What number do you want to find?")
numberToFind = Console.ReadLine()
For a = 1 To list.Length
If list(a) = numberToFind Then
Console.Write(comparisonNo)
Else
comparisonNo += 1
End If
Next
Console.ReadLine()
End Sub
End Module
答案 0 :(得分:3)
将“For a = 1 To list.Length”更改为“For a = 0 To list.Length - 1”。数组基于零。