rossi 發問時間: 電腦與網際網路程式設計 · 9 年前

VB 取亂數不重複,請幫忙修改程式...

以下程式為從1~42中取出六個數字,可否幫忙修改為不重複..

Private Sub Command1_Click()

If Command1.Caption = "請開獎" Then

Timer1.Interval = 0

Command1.Caption = "再一次"

Else

Timer1.Interval = 100

Command1.Caption = "請開獎"

End If

End SubPrivate Sub Form_Load()

Randomize

End Sub

Private Sub Timer1_Timer()

For i = 0 To 5

Label1(i).Caption = Int(Rnd() * 42 + 1)

Next i

End Sub

3 個解答

評分
  • march
    Lv 7
    9 年前
    最佳解答

    Private Sub Command1_Click()

    If Command1.Caption = "請開獎" Then

    Timer1.Interval = 0

    Command1.Caption = "再一次"

    Else

    Timer1.Interval = 100

    Command1.Caption = "請開獎"

    End If

    End SubPrivate Sub Form_Load()

    Randomize Timer

    End SubPrivate Sub Timer1_Timer()

    d:

    For i = 0 To 5

    Label1(i).Caption = Int(Rnd() * 42 + 1)

    Next i

    l = 0

    For j = 0 To 4

    For k = j + 1 To 5

    If Label1(j).Caption = Label1(k).Caption Then l = 1

    Next

    Next

    If l = 1 Then GoTo d

    End Sub

    2012-02-21 00:25:49 補充:

    抱歉 我只是五秒解決它的問題, 如果覺得不妥 用WHILE ---WEND 也行

    VB6 就是比較低級一點, 對不起喔!

  • 9 年前

    Private Sub Form_Click() '點擊表單測試

    Cls

    Dim p() As Integer

    p = GetRnds()

    For Each d In p

    Print d

    Next d

    End Sub

    Function GetRnds() As Integer()

    Randomize

    Dim v(5) As Integer

    Dim i As Integer, j As Integer

    For i = 0 To 5

    Do

    v(i) = Fix(Rnd * 6) + 1

    For j = 0 To i '檢查有沒有跟之前相同,

    If v(i) = v(j) Then Exit For

    Next j

    Loop While (j < i) '<~如果沒有提早離開for-loop, i=j, 就不會做do-loop

    Next i

    GetRnds = v

    End Function

    2012-02-20 11:07:33 補充:

    樓上-->「Private Sub Command1_Click()」是VB6

    ArrayList 是.Net 的東西

    2012-02-20 15:15:39 補充:

    '又無聊做一下另類.Net 做法, 上面兩個都是檢查有存在, 下面是抽取再塞回去

    Private NumList As New List(Of Byte)

    Private Sub ME_LOAD(s, e) 'Handles MyBase.load

    For i% = 1 To 42

    NumList.Add(i)

    Next i

    End Sub

    2012-02-20 15:17:12 補充:

    Private Function GetRnds(ByVal count%) As Byte()

    Randomize()

    Dim gotten(count - 1) As Byte

    For i% = 1 To count

    Dim index% = Math.Floor(Rnd() * NumList.Count)

    gotten(i) = NumList(index)

    NumList.RemoveAt(index)

    Next i

    NumList.AddRange(gotten)

    Return gotten

    End Function

    2012-02-21 00:13:25 補充:

    高階語言太常用Goto 不是一件好事喔..

    2012-02-21 00:33:33 補充:

    其實還不知道Timer 用意為何??

    如果不是為了製造顯示出不斷轉換的效果, 可以去掉

  • CSIRGO
    Lv 6
    9 年前

    timer1 修改如下

    Dim temp1 As Integer

    Dim da As New ArrayList

    da.Clear()

    For i = 0 To 5

    tx(i).Text = ""

    temp1 = Int(Rnd() * 42 + 1)

    Dim aa = da.IndexOf(temp1)

    If (aa = -1) Then

    da.Add(temp1)

    tx(i).Text = temp1

    Else

    i = i - 1

    End If

    Next i

    Timer1.Enabled = False

    將亂數取出來的值放入陣列比較使用即可

還有問題?馬上發問,尋求解答。