vb 有關隨機數不重覆出現的問題[等答]

2007-06-06 7:48 pm
如果是隨機整數在vb 上就是
int(rnd( )*整數)
但如果我整左第1個隨機數
唔想再執行時同佢重覆... 應該要點做?
(類似 我想做0 到20的隨機數列,但想是不重覆的)

回答 (3)

2007-06-07 6:02 pm
✔ 最佳答案
求不重複隨機數有兩個方法
方法一:標記法,就好像填六合彩的表格一樣,已經選了的編號,就會在表格中填黑了,那麼下次就不會再選這個號。

圖片參考:http://i200.photobucket.com/albums/aa23/wong196907/rnd2.jpg

方法二:順序查找法,就是每出一個數,都看一下前面是否已經出過。

圖片參考:http://i200.photobucket.com/albums/aa23/wong196907/rnd1.jpg

喜歡的話, 可以在最前面加入randomize, 使每次的隨機數種子都不同。
因為直接貼程式會爛, 所以改為貼圖。
2007-06-07 9:15 am
你係rnd之前加入randomize
Private Sub Command1_Click()
Randomize
MsgBox Int(Rnd * 20)
End Sub
2007-06-07 6:29 am
try to use a array to store what numbers have been generated. pls try following code.

Sub GenRandomNum(nTeam As Integer, nMin As Integer, nMax As Integer)
' Variable declare in initial
Dim aTeam(1 To 1024) As Integer
Dim aChk(1 To 1024) As Boolean
Dim nLoop, nTemp, i, j As Integer
Dim sShow As String
nLoop = 0
sShow = ""

' Generate random and check duplicate
Do
aTeam(nLoop + 1) = Int(nMax * Rnd()) + 1 - nMin
If Not aChk(aTeam(nLoop + 1)) Then
aChk(aTeam(nLoop + 1)) = True
nLoop = nLoop + 1
End If
If nLoop >= nTeam Then
Exit Do
End If
Loop

' Numbers sorting
For i = 1 To nTeam - 1
For j = 1 To nTeam - 1
If aTeam(j) > aTeam(j + 1) Then
nTemp = aTeam(j)
aTeam(j) = aTeam(j + 1)
aTeam(j + 1) = nTemp
End If
Next
Next
For i = 1 To nTeam
sShow = sShow & Trim(Str(aTeam(i))) & " "
Next

'Show result
MsgBox Trim(sShow)

End Sub

'Program for testing
Sub ChkSub()
Call GenRandomNum(20, 0, 100)
End Sub



hope can help u


收錄日期: 2021-04-12 21:42:46
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070606000051KK01183

檢視 Wayback Machine 備份