計(jì)算機(jī)等級(jí)考試二級(jí)VB常用算法(2):最值

字號(hào):

1、算法說(shuō)明
    在若干數(shù)中求值,一般先取第一個(gè)數(shù)為值的初值(即假設(shè)第一個(gè)數(shù)為值),然后,在循環(huán)體內(nèi)將每一個(gè)數(shù)與值比較,若該數(shù)大于值,將該數(shù)替換為值,直到循環(huán)結(jié)束。
    求最小值的方法類同。
    求若干數(shù)平均值,實(shí)質(zhì)上就是先求和,再除以這些數(shù)的個(gè)數(shù)。
    應(yīng)用舉例
    隨機(jī)產(chǎn)生n個(gè)1-100(包括1和100)的數(shù),求它們的值、最小值和平均值。
    以下是引用片段:
    Private Sub Command1_Click()
    Dim n As Integer, i As Integer, min As Integer, max As Integer, aver As Single, s As Integer
    n = Val(InputBox("輸入個(gè)數(shù):"))
    s = Int(Rnd * 100) + 1
    max = s
    min = s
    aver = s
    Print "第1個(gè)數(shù)是:" & s
    For i = 2 To n
    s = Int(Rnd * 100) + 1
    Print "第" & i & "個(gè)數(shù)是:" & s
    If s > max Then max = s
    If s < min Then min = s
    aver = aver + s
    Next i
    aver = aver / n
    Print "max="; max; "min="; min; "aver="; aver
    End Sub
    解題技巧
    值、最小值、平均值類型題目往往和數(shù)組放在一起考!有的不僅求這些值,還要對(duì)具有值或者最小值的行或列或者某個(gè)元素進(jìn)行處理,這時(shí)就要在記錄、最小值時(shí),同時(shí)記錄該值所在的行號(hào)和列號(hào)。
    2、實(shí)戰(zhàn)練習(xí)
    1) 補(bǔ)充代碼
    本程序的功能是在二維數(shù)組中查找鞍點(diǎn)元素,即該元素在所在行中為,且在所在列中為最小。在一個(gè)數(shù)組中可能存在,也可能不存在這樣的元素。數(shù)組各元素的值從文件data.txt中讀取。
    以下是引用片段:
    Private Sub Form_Click()
    Dim a(3,3) As Integer,i As Integer,j As Integer
    Dim maxvr As Integer,col As Integer, As Integer
    Open data.txt For Input As #1
    For i=1 To 3
    For j=1 To 3
    Input #1,a(i,j)
    Print a(i,j);
    Next j
    Print
    Next i
    For i=1 To 3
    maxvr= (1)
    col=1
    For j=2 To 3
    If maxvr
    maxvr= (2)
    col=j
    End If
    Next j
    For j=1 To 3
    If maxvr>a(j,col) Then (3)
    Next j