VB的数组问题~高手帮帮忙啊~~

来源:百度知道 编辑:UC知道 时间:2024/05/17 08:09:22
写出一个程序,使得每输入一个数后,数组总保持有序如:
输入8 输出8
输入8,4 输出4,8
输入8,4,5 输出4,5,8
………………………………
~这是我遍的程序~~帮帮忙看看哪里错了啊

Private Sub Command1_Click()
Dim n As Integer
Dim a As Integer
Dim l() As Integer
Dim c As Integer

For i = 1 To n
a = InputBox("输入")
If i = 1 Then Print a
If i > 1 Then
For m = 1 To n - 1
For j = 1 To n - m
If l(j) > l(j + 1) Then
t = l(j)
l(j) = l(j + 1)
l(j + 1) = t
Print l(j)
End If

Next j
Next m
End If

Next i
end sub
2楼,这里我的l怎么定义大小,题目要求就没有定义输多少个数字
2楼的朋友~可以帮我具体改下怎么在插入数组的元素吗?我看了你的文章~大概理解了你的意思,但是我不知道具体因该怎么改~谢谢啊

数组l()没有定义大小,要用redim重新定义大小才能用,如果想在重新定义大小时,保留原数组中的数据,请加上preserve关键字.具体可以查看msdn,也可以到我的blog中看看文章:"在vb中实现对一维数组元素的插入和删除操作"
会对你有帮助的!我的blog:http://hi.baidu.com/privateblog

对楼主补充问题的回答
所以你需要用到preserve关键字,来不停的增大数组的大小,而保留原有数组里面的数据
例如:redim preserve l(0)
redim preserve l(1)
你每插入一个数,就把数组增大1
你可以去好好研究研究我的文章
把代码给你吧

Dim n As Integer
Dim a As Integer
Dim L() As Integer
Dim c As Integer
Dim InsertPos As Integer '插入元素的位置
n = 4 '输入多少个数据,你自己可以根据需要来更改
For i = 1 To n
a = InputBox("请输入一个整数")
If i = 1 Then
ReDim L(0)
L(0) = a
Print a
End If
If i > 1 Then
InsertPos = UBound(L) + 1
For m = 0 To UBound(L)
If a < L(m) Then
InsertPos = m
Exit For
End If
Next
Call InsertEle(L