回覆列表
-
1 # 憶147857972
-
2 # 文文愛吃肉
1、在這裡我們透過編寫程式找出10個數中的最大值與最小值。開啟vb6.0,新建一個標準EXE
2、在屬性視窗將Form1的Caption屬性改成”陣列求最值“
3、接著編寫一個窗體的單擊事件,程式碼如下:
Option Explicit
Option Base 1
Private Sub Form_click()
Dim a(), x, max, min, i%, n%
a = Array(45, 98, 79, 90, - 23, 45, 67, 89, 75, 109)
n = UBound(a)
Print "陣列的資料為:"
For i = 1 To n
Print a(i)
Next i
Print
max = a(1): min = a(1)
For i = 2 To n
If a(i) > max Then max = a(i)
If a(i) < min Then min = a(i)
Next i
Print "最大值為:"; max; "最小值為:"; min
End Sub
5、下圖中用紅圈標識出的,就表示在這組陣列中將第一個數賦值為max或者min,然後逐次與後面的進行比較如果遇到比它大或者小就把這個數賦值給max或者min.
6、接著我們可以修改程式碼中的資料(300, 205, 561, 156, 789, 456, 123, 423, 258, -147),然後再來執行一下程式。
用VB編寫程式對一組陣列求最值的操作步驟
Private Sub Command1_Click()
Dim a(10) As Integer
Dim Tmp As Integer, Tmp1 As Integer
Me.Cls
For i = 0 To 10
Randomize
a(i) = Int(Rnd * 100)
Me.Print a(i);
Next i "隨機產生一組數
Tmp = a(0)
For i = 0 To 10
If a(i) > Tmp Then Tmp1 = Tmp: Tmp = a(i): a(i) = Tmp1
Next
Me.Print vbCrLf & "最大值:shu" & Tmp
End Sub