VB求数组中最大值和它的位置
我写了个能求最大值,但不知道怎么求它的原来位置
请补充一下。
Private Sub Command1_Click()
Dim a(1 To 10) As Integer, work As Boolean, i As Integer, j As Integer, x As Integer
Randomize
For i = 1 To 10
a(i) = Int((90 * Rnd) + 10)
Print a(i)
Next i
For i = 10 To 2 Step -1
work = True
For j = 1 To i - 1
If a(j) > a(j + 1) Then
x = a(j)
a(j) = a(j + 1)
a(j + 1) = x
work = False
End If
Next j
If work Then Exit For
Next i
Text1.Text = a(10)
End Sub 展开
定义一个q1,初始值为a(0),每次判断a(j) > a(j + 1) 成立时,q1=j
此时q1就为所求位置,但是初始位置是0,所以要准确时q1=q1+1
如下所示:
Private Sub Command1_Click()
Cls
Dim a(1 To 10) As Integer, b(1 To 10) As Integer, work As Boolean, i As Integer, j As Integer,
x As Integer
Randomize
For i = 1 To 10
a(i) = Int((90 * Rnd) + 10)
Print a(i)
b(i) = a(i)
Next i
For i = 10 To 2 Step -1
work = True
For j = 1 To i - 1
If a(j) > a(j + 1) Then
x = a(j)
a(j) = a(j + 1)
a(j + 1) = x
work = False
End If
Next j
If work Then Exit For
Next i
Text1.Text = a(10)
For k = 1 To UBound(a)
If b(k) = a(10) Then
MsgBox "原来位置:" & k, 64, "提示!"
Exit For
End If
Next k
扩展资料:
有两种方法定义数组:
1、知道数组的元素个数,那么直接定义。
dim a(9) as integer
2、暂时不知道元素个数,或者该数组应用在多个地方,那么如下定义。
dim a() as integer
在使用的时候,再重定义一下就可以了。
ReDim a(9)
数组的类型可以和变量的类型一样的。
dim a(0 to 9) as string '表示定义了一个包含10个元素的字符串型的数组,数组名为:a
参考资料来源:百度百科-Visual Basic
Private Sub Command1_Click()
Cls
Dim a(1 To 10) As Integer, b(1 To 10) As Integer, work As Boolean, i As Integer, j As Integer, x As Integer
Randomize
For i = 1 To 10
a(i) = Int((90 * Rnd) + 10)
Print a(i)
b(i) = a(i)
Next i
For i = 10 To 2 Step -1
work = True
For j = 1 To i - 1
If a(j) > a(j + 1) Then
x = a(j)
a(j) = a(j + 1)
a(j + 1) = x
work = False
End If
Next j
If work Then Exit For
Next i
Text1.Text = a(10)
For k = 1 To UBound(a)
If b(k) = a(10) Then
MsgBox "原来位置:" & k, 64, "提示!"
Exit For
End If
Next k
定义一个q1,初始值为a(0),每次判断a(j) > a(j + 1) 成立时,q1=j
此时q1就为你的位置,但是初始位置是0,所以要准确时q1=q1+1