代码:
Dim max, min As Integer
Dim avg As Double
Private Sub Command1_Click()
Dim num(10) As Integer
Text1.Text = ""
Label4.Caption = ""
Label5.Caption = ""
Label6.Caption = ""
Dim i, j, temp, sum As Integer
sum = 0
For i = 1 To 10
num(i) = Int(Rnd * (100 + 1))
sum = sum + num(i)
Text1.Text = Text1.Text &num(i) &Space(4)
Next i
For i = 1 To 10
For j = 1 To 10 - i
If num(j) <num(j + 1) Then
temp = num(j)
num(j) = num(j + 1)
num(j + 1) = temp
End If
Next j
Next i
max = num(1)
min = num(10)
avg = sum * 1# / 10
End Sub
Private Sub Command2_Click()
If Text1.Text = "" Then
MsgBox "没有数组,无法计算!"
Else
Label4.Caption = max
Label5.Caption = min
Label6.Caption = avg
End If
End Sub
设计好的窗体:
程序运行的窗体:
求最大值就是,取第一个数给临时变量,然后用临时变量去跟数组的数比较,如果数组的值大于临时变量的值,则用数组的值替换临时变量的值,数组检索完成最后得到的就是数组里面最大的值。取最小值也是一样的道理。例子,取最大最小值:
Private Function Max(Data() As Double) As Double'求实数最大值函数
Dim i As Long
Dim x1 As Long, x2 As Long
x1 = LBound(Data)
x2 = UBound(Data)
Max = Data(x1)
For i = x1 To x2
If Data(i) >= Max Then Max = Data(i)'如果数组当前值比Max值大,替换Max中的值
Next
End Function
Private Function Min(Data() As Double) As Double'求实数最小值函数
Dim i As Long
Dim x1 As Long, x2 As Long
x1 = LBound(Data)
x2 = UBound(Data)
Min = Data(x1)
For i = x1 To x2
If Data(i) <= Min Then Min = Data(i)'如果数组当前值比Min值大,替换Min中的值
Next
End Function
Private Sub Command1_Click()'点击按钮求随机数组最大值
Dim a As Integer, b As Integer
Dim Maxs As Double, Mins As Double
Dim temps(100) As Double
Randomize '定义生成的随机数为不重复模式
For i = 0 To 100
If Rnd() >0.5 Then temps(i) = 100 * Rnd() Else temps(i) = -100 * Rnd() '生成101个100以内的随即实数
Next
Maxs = Max(temps) '调用Max函数求实数最大值
Mins = Min(temps) '调用Min函数求实数最小值
Me.Cls
Me.Print Maxs '显示实数到窗体
Me.Print Mins
End Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)