2

您好,我在 0 和 10 之间有 5 个唯一数字,我正在执行以下操作:

Dim RandomClass As New Random()
Dim RandomNumber As Integer
For counter As Integer = 0 To 5
    RandomNumber = RandomClass.Next(0, 10)
    MsgBox(RandomNumber )
Next

有时它有效,我得到这些数字:“1,7,4,9,3”,但有时我得到一个重复的数字,如:“5,2,3,2,7”

我怎样才能确保每次都有唯一的数字?

谢谢你。

4

4 回答 4

6

用于记住已经打印出来的数字HashSet(Of Integer)

Dim RandomClass As New Random()
Dim RememberSet As New HashSet(Of Integer)

Dim RandomNumber As Integer

While RememberSet.Count < 5
    RandomNumber = RandomClass.Next(0, 10)
    If RememberSet.Add(RandomNumber) Then
        MsgBox(RandomNumber)
    End If
End While
于 2013-08-17T21:57:39.793 回答
2

只是为了好玩,另一种方法,制作一个从 0 到 10 的整数列表,使用随机生成器在该列表中获取索引,打印该数字并从列表中删除。将随机数的生成保持在限制范围内

Dim numbers = Enumerable.Range(0, 11).ToList()
Dim RandomClass As New Random()
Dim RandomIndex As Integer
For counter As Integer = 1 To 5
    RandomIndex = RandomClass.Next(0, numbers.Count)
    MsgBox(numbers(RandomIndex))
    numbers.RemoveAt(RandomIndex)
Next
于 2013-08-17T22:14:08.990 回答
0

我建议添加一个种子,这样随机数就不会重复。

Dim RandomClass As New Random(DateTime.Now.Ticks)
Dim RememberSet As New HashSet(Of Integer)

Dim RandomNumber As Integer

While RememberSet.Count < 5
    RandomNumber = RandomClass.Next(0, 10)
    If RememberSet.Add(RandomNumber) Then
        MsgBox(RandomNumber)
    End If
End While
于 2014-07-24T10:19:58.020 回答
0

尝试以下:

 Sub Main()

    Dim a As String() = New String(2) {}
    Dim b As String
    Dim c As Integer = 0
    Dim d As String = " "
    Do
        Console.Clear()
        Console.Write("Enter your name:")
        a(c) = Console.ReadLine()
        c += 1

    Loop Until c = 3
    For Each d In a
        Console.Write(" " & d)
    Next
    Console.ReadLine()
于 2017-07-05T12:10:28.313 回答