計算機等級考試二級VB常用算法(2):最值
1.算法描述
在對幾個數求值時,一般取第一個數作爲值的初始值(即假設第一個數就是值)。然後,將每個數字與循環中的值進行比較。如果數字大於值,則它將被替換爲值,直到循環結束。
求最小值的方法是相似的。
求幾個數的平均值,本質上就是先求和,然後除以這些數的個數。
應用示例
從1到100(含)隨機生成N個數,求它們的值、最小值、平均值。
以下是帶引號的片段:
private subcommand 1 _ click()
dim n As integer,I as integer,min as integer,max as integer,averas single,As integer
n = val (InputBox("輸入數:")))
s = int(RND * 100) 1
max = s
min = s
aver = s[第一次打印數" is:"&s
for I = .if s < min Then min = s
aver = aver s
Next I
aver = aver/n
Print" max =";max" min =";min" aver =";aver
End Sub
解決問題的技巧
數值,最小值,平均值經常和數組一起測試!有些不僅尋找這些值,而且還処理具有值或最小值的行或列或元素。此時,在記錄最小值時,應同時記錄該值的行號和列號。
2.實踐練習
1)補充代碼
這個程序的作用是尋找二維數組中的鞍點元素,即元素在行,最小的在列。數組中可能有也可能沒有這樣的元素。數組中每個元素的值都是從文件data.txt中讀取的
以下爲引用片段:
private subform _ 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到3
maxvr =(1)
col = 1
For j = 2到3
If maxvr
maxvr =(2)
col = j
End If
Next j
For j = 1到3
If maxvr >
0條評論