作业帮 > 数学 > 作业

VB 最接近的数字我有2个数组 a1 和 a2 和 2个 整形变量 o p 2个数组的元素个数我不知道要求在a2数组中

来源:学生作业帮 编辑:搜搜考试网作业帮 分类:数学作业 时间:2024/06/08 19:31:55
VB 最接近的数字
我有2个数组 a1 和 a2 和 2个 整形变量 o p
2个数组的元素个数我不知道
要求
在a2数组中 找出与a1数组最接近的2个数字
剧烈
a1(1) = "3"
a1(2) = "5"
a2(1) = "1"
a2(2) = "5"
a2(3) = "7"
a2(4) = "10"
这样 因为a1元素有2个 所以 o p 值也有2个
我要求只要这样
msgbox o & p
上面的对话框会出现2次
第一次值 应该是 1 和5 因为在数组a2中 最前面的与1最接近 最后的与5最接近
第二次值 应该是 5 和7 因为在数组2中 5就是他本身 是最最接近的 相邻的是7
VB 最接近的数字我有2个数组 a1 和 a2 和 2个 整形变量 o p 2个数组的元素个数我不知道要求在a2数组中
Private Sub Command1_Click()
Dim a1() As Long
Dim a2() As Long
Dim i As Long
Dim j As Long
Dim o As Long,p As Long
Dim distance() As Long
Dim minDistance() As Long
Dim minIndex() As Long
ReDim a1(1 To 2)
ReDim a2(1 To 4)
a1(1) = 3
a1(2) = 5
a2(1) = 7
a2(2) = 5
a2(3) = 1
a2(4) = 10
For i = LBound(a1) To UBound(a1)
ReDim distance(LBound(a2) To UBound(a2))
ReDim minDistance(0 To 1)
ReDim minIndex(0 To 1)
'取距离
For j = LBound(a2) To UBound(a2)
distance(j) = Abs(a2(j) - a1(i))
Next j
'选最小值
minIndex(0) = LBound(distance)
minDistance(0) = distance(minIndex(0))
For j = LBound(distance) To UBound(distance)
If (distance(j) < minDistance(0)) Then
minIndex(0) = j
minDistance(0) = distance(j)
End If
Next j
'选次小值
minIndex(1) = LBound(distance)
minDistance(1) = distance(minIndex(1))
For j = LBound(distance) To UBound(distance)
If (distance(j)