vb 有關隨機數不重覆出現的問題[等答]
如果是隨機整數在vb 上就是
int(rnd( )*整數)
但如果我整左第1個隨機數
唔想再執行時同佢重覆... 應該要點做?
(類似 我想做0 到20的隨機數列,但想是不重覆的)
回答 (3)
你係rnd之前加入randomize
Private Sub Command1_Click()
Randomize
MsgBox Int(Rnd * 20)
End Sub
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 備份