随即生成n个数

Private Sub command1_click()

    Dim a() As Integer

        n = InputBox("请输入一个整数n,n>=1")

    ReDim a(1 To n)

    Dim p As String

    Randomize

        p = ""

    For i = 1 To n

        Do

            x = Int(Rnd * 90) + 10

            yes = 0

            For j = 1 To i - 1

                If x = a(j) Then yes = 1: Exit For '防止出现重复的数

            Next

        Loop While yes = 1

        a(i) = x

        p = p & Str(a(i)) & ","

    Next

    Label1.Caption = LTrim(Left(p, Len(p) - 1))

End Sub

 

 

添加注释后的代码

Private Sub command1_click()

    Dim a() As Integer 'a用来存放生成的随机n个正整数

        n = InputBox("请输入一个整数n,n>=1")

    ReDim a(1 To n)

    Dim p As String 'p表示随机生成的n个整数

    Randomize

        p = ""

    For i = 1 To n '生成n个整数

        Do

            x = Int(Rnd * 90) + 10 '存放中间生成的一个随机数,范围是099,包括0也包括99

            yes = 0 '用来判断生成的x要还是不要,0表示要,1表示不要

            For j = 1 To i - 1 '对要生成的第i个随机数进行检测,检测结果放在yes

                If x = a(j) Then yes = 1: Exit For '防止出现重复的数

            Next

        Loop While yes = 1

        a(i) = x

        p = p & Str(a(i)) & ","

    Next

    Label1.Caption = LTrim(Left(p, Len(p) - 1)) 'label1现实最终的随机生成的n个整数

End Sub

你可能感兴趣的:(随即生成n个数)