当前位置:编程学习 > VB >>

vb编程问题

编写一个find()函数,能够查找用户输入的数是否在一个随机数组中,若在数组中,则将其位置显示出来。例如,a数组中有随机产生的5个数3、8、9、5、2.如果用户输入9,调用find()函数后能够显示:9在数组a中,是第3个数
追问:对吗?是你自己写的吗?不要骗我啊!
答案:
Private Declare Function GetTickCount Lib "kernel32" () As Long

Private Function find(arr() As Long, ByVal item As Long) As Long
Dim i As Long
find = -1
If UBound(arr) - LBound(arr) < 0 Then Exit Function
For i = LBound(arr) To UBound(arr)
If arr(i) = item Then
find = i - LBound(arr) + 1
Exit Function
End If
Next
End Function

Private Sub Command1_Click()
Dim i As Long, cnt As Long, arr() As Long, sArr As String, tmpStr As String
Dim item As Long, index As Long
cnt = 5
ReDim arr(1 To cnt)
For i = 1 To cnt
arr(i) = CLng(Rnd * 1000) Mod 100 ' 100以内的随机数

sArr = sArr & " " & arr(i)
Next
tmpStr = InputBox("数组为: " & sArr & ", 请输入要找的值: ", "^^")
If IsNumeric(tmpStr) = False Then Exit Sub ' 不是数字
item = CLng(tmpStr)

index = find(arr, item)
If index = -1 Then
tmpStr = item & " 不在数组中。"
Else
tmpStr = item & " 在数组中, 是第 " & index & " 个。"
End If
MsgBox tmpStr, vbInformation, "^^"
End Sub

Private Sub Form_Load()
Randomize GetTickCount
End Sub
Dim arr() As String
Private Sub Form_Load()
Dim a As String
a = InputBox("输入一个数列用空格隔开")
arr = Split(a)
find (Val(InputBox("输入要查找的数字")))
End Sub

Private Function find(num As Integer) As Integer
Dim i As Integer
For i = 0 To UBound(arr)
If Val(arr(i)) = num Then MsgBox num & "在数组a中的第" & i + 1 & "个数"
Next
End Function
----------------------------------------
Dim arr() As String 需要定义为全局变量

上一个:vb编程开发
下一个:VB编程问题

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,