注册 登录
编程论坛 VB6论坛

为什么还会产生重复的数字

magicsky1394 发布于 2013-05-04 22:58, 434 次点击
做了一个随机抽取学生学号的程序,通过文本框输入学生总人数和要抽取的学生人数,抽取学生(包括消除重复学号),把抽出的学号排序,最后输出。
运行过程中,为什么仍然会产生重复的学号?
Private Sub Command1_Click()
    Dim Total As Integer, Sel As Integer, c()  As Integer
    Dim i As Integer, j As Integer, Temp As Integer
    Total = Val(Text1.Text)
    Sel = Val(Text2.Text)
    ReDim c(1 To Sel)
    c(1) = Int(Rnd * Total) + 1
    For i = 2 To Sel
        c(i) = Int(Rnd * Total) + 1
        For j = 1 To (i - 1)
            Do While c(i) = c(j)
               c(i) = Int(Rnd * Total) + 1
            Loop
        Next j
    Next i
    For i = 1 To (Sel - 1)
        For j = (i + 1) To Sel
            If c(i) > c(j) Then
                Temp = c(i)
                c(i) = c(j)
                c(j) = Temp
            End If
        Next j
    Next i
    Text3.Text = "以下学号的同学需要交作业:"
    For i = 1 To Sel
        Text3.Text = Text3.Text & vbCrLf & Format(c(i), "00")
    Next i
End Sub

[ 本帖最后由 magicsky1394 于 2013-5-4 22:59 编辑 ]
3 回复
#2
seafish0112013-05-05 00:43
加个randomize进去
#3
lowxiong2013-05-05 08:09
算法错误
            Do While c(i) = c(j)
               c(i) = Int(Rnd * Total) + 1
            Loop
这只能保证当前c(j)<>c(i),却不能保证c(i)也能不等于已经比较了的c(j),即不能保证c(i)<>c(j-1)。主要是do循环和for循环用反了,正确代码如下(验证时用text1=text2,即全班全部交作业来验证):
Private Sub Command1_Click()
    Dim Total As Integer, Sel As Integer, c()  As Integer, f As Boolean
    Dim i As Integer, j As Integer, Temp As Integer
    Total = Val(Text1.Text)
    Sel = Val(Text2.Text)
    ReDim c(1 To Sel)
    For i = 1 To Sel
      Do
        c(i) = Int(Rnd * Total) + 1
        f = False
        For j = i - 1 To 1 Step -1
          If c(i) = c(j) Then
            f = True
            Exit For
          End If
        Next
      Loop While f
    Next
    For i = 1 To (Sel - 1)
        For j = (i + 1) To Sel
            If c(i) > c(j) Then
                Temp = c(i)
                c(i) = c(j)
                c(j) = Temp
            End If
        Next j
    Next i
    Text3.Text = "以下学号的同学需要交作业:"
    For i = 1 To Sel
        Text3.Text = Text3.Text & vbCrLf & Format(c(i), "00")
    Next i
End Sub
#4
magicsky13942013-05-05 09:03
明白了,非常感谢!
1