1、实验十一 数组(续)实验目的:1、 掌握动态数组与静态数组的使用差别;2、 掌握动态数组定义和使用方法;3、 掌握控件数组的使用方法。实验内容:(13 题为必做题,45 题任选一题)1、 分别用选择排序法和冒泡排序法实现有 N 个元素数 组的排序。N 由键盘输入,数 组元素的值在 1200 之间,随机产生。Private Sub form_click()RandomizeDim a(), i%, J%, N%, T%, k%N = InputBox(“请输入一个数“)ReDim a(N)a(N) = Int(Rnd * 200 + 1)N = UBound(a)For i = 1 To Na(
2、i) = Int(Rnd * 200 + 1)NextFor i = 0 To N - 1T = iFor J = i + 1 To NIf a(T) a(J) Then T = JNext Jk = a(i)a(i) = a(T)a(T) = kNext iFor i = LBound(a) To UBound(a)Print a(i);If i Mod 5 = 0 Then PrintNextEnd SubPrivate Sub command1_click()RandomizeDim a(), i%, J%, N%N = InputBox(“请输入一个数“)ReDim a(N)a(N)
3、= Int(Rnd * 200 + 1)N = UBound(a)For i = 1 To Na(i) = Int(Rnd * 200 + 1)NextFor i = 0 To N - 1For J = 0 To N - 1 - iIf a(J) a(J + 1) Thenk = a(J)a(J) = a(J + 1)a(J + 1) = kEnd IfNext JNext iFor i = 0 To NPrint a(i);If i Mod 5 = 0 Then PrintNextEnd Sub2、利用 Array 函数给数组 a 赋值(数组元素的个数及每个元素的值自己设定),从键盘 上输入
4、一个数据,在数组中进行查找,如果数组中有,则删除数组中的这个元素,如果没有则提示 “没有这个数”。【提示】删除数组中的某个元素就是将这个元素之后的元素分别往前移动一个位置,如数组原来是 11,22,33,44,55,66,77,88 共 8 个元素,如果要删除值为 44 的元素,其实就是将后面的 55,66,77,88 往前移一位,覆盖原来的数据,然后再重新声明数组有 7 个元素即可。【思考】如果将数组元素读入列表框再做插入或删除其中一个元素,应该怎样编程?Private Sub Form_Click()Dim A(), i%, k%, x%, n%A = Array(30, 42, 34,
5、23, 25, 24, 34, 55, 66)n = UBound(A)x = Val(Text1)For k = 0 To nIf x = A(k) Then Exit ForNext kIf k n Then MsgBox (“找不到此数据“): Exit SubFor i = k + 1 To nA(i - 1) = A(i)Next in = n - 1ReDim Preserve A(n)For i = 0 To nPrint A(i);Next iEnd Sub3、输入一系列字符串,按递减次序排列。程序的运行界面如下所示。【提示】(1)要声明窗体级变量 n(表示放若干个字符串的计数
6、器)及一个字符串数组。(2)每输入一个字符串,按 Enter 键后将 Text 的内容放到数组中,可用事件:Private Sub Text1_KeyPress(KeyAscii As Integer)If KeyAscii = 13 ThenEnd IfEnd Sub图形框(3) 单击“ 排序”按钮, 进行排序并显示在图形框中。(4) 字符的排序与数字的排序原理是一样的。Dim n%, s(100) As StringPrivate Sub Form_Load()Command1.Caption = “排序“Picture1.AutoRedraw = TrueText1 = “End Sub
7、Private Sub text1_keypress(keyascii As Integer)If n = 100 Then Exit SubIf keyascii = 13 Thens(n) = Text1Text1 = “n = n + 1End IfEnd SubPrivate Sub Command1_Click()Picture1.Clsn = n - 1For i = 0 To n - 1For j = i + 1 To nIf s(j) “ ThenIf s(i) 0 ThenText1.Text = Left(Text1.Text, Len(Text1.Text) - 1)En
8、d IfEnd SubPrivate Sub cmdClear_Click()Text1.Text = “End Sub5、做一个类似下图界面的简单计算器。Dim a As SingleDim b As Single, x As StringPrivate Sub Command1_Click(index As Integer)Text1.Text = Text1.Text & Command1(index).CaptionEnd SubPrivate Sub Command2_Click(index As Integer)a = Val(Text1.Text)x = Command2(ind
9、ex).CaptionText1.Text = “End SubPrivate Sub Cmdclear_Click()Text1 = “End SubPrivate Sub Command3_Click()b = Val(Text1.Text)Select Case xCase “+“Text1.Text = a + bCase “-“Text1.Text = a - bCase “*“Text1.Text = a * bCase “/“If b = 0 ThenMsgBox “除数不能 为零!“Text1.Text = “ElseText1.Text = a / bEnd IfEnd SelectEnd SubPrivate Sub Command4_Click()EndEnd Sub【提示】(1)控件数组 cmdNum 包括 10 个控件,下标分别与 09 这 10 个数字对应。按下控件数组的某个按 钮时,用其元素的下 标值对应组成数据。(2)cmdCount 也是包含了四个元素的控件数组,分 别表示”+” 、”、 ”*”、”/”运算符,可用 Select Case 语句判断并做出不同的操作。