程序如下:
Private Sub Form_Activate()
Dim a(1 To 10) As Integer '定义存放10个小于等于100的整数数组
Dim sum, i, max, min As Integer '定义sum存放10个数的和,min放10个数中最小值,max放最大值,i循环控制变量
Dim aver As Single '定义aver放平均值
sum = 0
max = 0
min = 100
Randomize
For i = 1 To 10 '生成随机数存入数组,并求出和、最大值、最小值
a(i) = Int(Rnd * 100 + 1)
sum = sum + a(i)
Print a(i)
If a(i) > max Then max = a(i)
If a(i) < min Then min = a(i)
Next i
aver = sum / 10
Print "平均数是" & aver
For i = 1 To 10 '逐渐改变最大值、最小值与平均值最接近的
If (a(i) <= max) And (a(i) > aver) Then max = a(i)
If (a(i) >= min) And (a(i) < aver) Then min = a(i)
Next i
If (max - aver) > (aver - min) Then '找到最接近的值
Print "最接近平均值得数是" & min
Else
If (max - aver) < (aver - min) Then
Print "最接近平均值得数是" & max
Else
Print "最接近平均值得数是" & min & vbTab & max
End If
End If
End Sub
运行结果如下:
Private Sub Command1_Click()
Dim m(9) As Integer
Dim a As Integer
Dim i As Integer
Dim x As Integer
Dim y As Integer
a = 0
For i = 0 To 9
m(i) = 10 + Int(Rnd * 89) '保存在数组中
x = x + m(i)
Next
y = x / 10
Text1.Text = y '平均数
Text2.Text = m(0) & "," & m(1) & "," & m(2) & "," & m(3) & "," & m(4) & "," & m(5) & "," & m(6) & "," & m(7) & "," & m(8) & "," & m(9)
a = m(0)
For i = 0 To 8
If Abs(m(i) - y) < Abs(m(i + 1) - y) Then
a = m(i)
m(i) = m(i + 1)
m(i + 1) = a
End If
Next
Text3.Text = a '最接近的数字
End Sub