现在用VB6.0实现——随机产生K个数并排序
程序说明:这个程序分两步骤说明,
Option Explicit
Private Sub Command1_Click()
Dim a() As Integer '定义数组变量用来盛放产生的K个数值,因为K个数值不确定故为动态数组
Dim k As Integer '用来盛放变两个数
Dim m As Integer '用来盛放下限
Dim n As Integer '用来存放上限
Dim max As Integer '用来存放最大值
'键盘输入变量值
k = InputBox("请输入需要产生多少个数")
m = InputBox("请输入下限")
n = InputBox("请输入上限")
'获取定值K值之后数组个数确定,重新定义数组变量
ReDim a(0 To k - 1)
'为了化繁为简,把问题分成三部分:(1.随机产生K个不重复的数;2。输出每一个数;3比较出最大值)并且用函数调用的方法各个击破
Call rndinteger(a(), m, n)
Call printarray(a())
max = callmax(a())
Print "这些数种最大的数是" & Str(max)
End Sub
Public Function rndinteger(a() As Integer, m As Integer, n As
Integer) As Integer
Dim c As Integer '用来保存刚刚产生的随机整数
Dim flag As Integer '标志 是否重复,重复为1,不重复为0
Dim i, j
Dim temp As Integer
'先处理特殊的;第一个不重复的数
temp = Int(m + (n - m) * Rnd() + 1)
c = temp
a(0) = c
'处理第二个以后可能重复的数
For i = 1 To UBound(a)
c = Int(m + (n - m) * Rnd + 1)
a(i) = c
'默认不重复,即flag=0
'判断此时产生的第i数是否与以前的i-1个数重复
For j = 0 To i - 1
If a(i) = a(j) Then
flag = 1
Exit For
Else
flag = 0
End If
Next j
If flag = 1 Then i = i - 1
Next i
End Function
Public Function callmax(a() As Integer) As Integer
Dim max As Integer
Dim i As Integer
'假设第一个数是最大值
max = a(0)
For i = 1 To UBound(a)
If max < a(i) Then
max = a(i)
End If
Next i
callmax = max
End Function
Public Function printarray(a() As Integer)
Dim x As Variant
For Each x In a()
Print x
Next
End Function