输入任意数,单击command2时,在text2中显示其位置,如没有该数,则提示该数不存在。请问下面这段程序有什么错吗?怎么会提示下表越界。有时候我改了之后却发现出现随机数的重复率高得可怕。
Option Base 1
Private Sub command1_click()
Dim a(10) As Integer
Dim temp As Long
For i = 1 To 10
a(i) = Int(Rnd * 100 + 0.5)
Next i
Text1.Text = a(1) & Space(2) & a(2) & Space(2) & a(3) & Space(2) & a(4) & Space(2) & a(5) & Space(2) & a(6) & Space(2) & a(7) & Space(2) & a(8) & Space(2) & a(9) & Space(2) & a(10)
End Sub
Private Sub command2_click()
Dim a()
Dim much As Long, temp As Long
much = Val(InputBox("请输入一个整数"))
For i = 1 To 8
For j = i + 1 To 9
a = Array(Text1.Text)
If a(i) > a(j) Then
temp = a(i)
a(j) = temp
a(i) = a(j)
End If
Next j
Next i
low = 1: Top = 10: t = Int((Top + low) / 2)
For i = 1 To 10
If much = a(t) Then
Text2.Text = a(t)
ElseIf much > a(t) Then
low = t + 1
ElseIf much < a(t) Then
Top = t - 1
Else
Text2.Text = "该数不存在于数组中"
End If
Next i
End Sub
那么该怎么 办呢
追答你的程序中,排序部分有问题,折半查找部分也存在问题。如下程序在你源程序的基础上,进行了修改。
Option Base 1
Private Sub command1_click()
Dim a(10) As Integer
Dim temp As Long
For i = 1 To 10
a(i) = Int(Rnd * 100 + 0.5)
Next i
Text1.Text = a(1) & Space(2) & a(2) & Space(2) & a(3) & Space(2) & a(4) & Space(2) & a(5) & Space(2) & a(6) & Space(2) & a(7) & Space(2) & a(8) & Space(2) & a(9) & Space(2) & a(10)
End Sub
Private Sub command2_click()
Dim a As Variant
Dim much As Long, temp As Long
much = Val(InputBox("请输入一个整数"))
a = Split(Text1.Text, " ")
For i = 0 To 8
For j = i + 1 To 9
If a(i) > a(j) Then
temp = a(i)
a(i) = a(j)
a(j) = temp
End If
Next j
Next i
low = 0: Top = 9
f = 0
Do
t = Int((Top + low) / 2)
If much = a(t) Then
f = 1
Else
If much > a(t) Then
low = t + 1
Else
Top = t - 1
End If
End If
Loop While (low < Top) And (f = 0)
If f = 1 Then
Text2.Text = a(t)
Else
Text2.Text = "该数不存在于数组中"
End If
End Sub