我正在制作公牛和奶牛游戏,我想随机生成一个有四个不同数字的数字。
Randomize()
Do
Random = Int(9000 * Rnd()) + 1000
'If (hasDupes = True)
randomTwo = Random
For i = 0 To randomTwo.Length - 1
For j = 0 To randomTwo.Length - 1
If randomTwo(i) = randomTwo(j) Then
dupes = False
Exit For
End If
Next
Next
Loop Until dupes = True
^这就是我到目前为止所做的,但它不起作用。如果有重复的字符或我的错误在哪里,我有什么功能可以找到吗?
答案 0 :(得分:0)
这将返回四个唯一的数字。
Sub unique4()
Dim n(1 To 4) As Integer
Dim i As Integer
Dim t As Integer
Dim hr as Boolean
n(1) = 9 * Rnd()
i = 2
Do
hr = False
n(i) = 9 * Rnd()
For t = 1 To i - 1
If n(t) = n(i) Then
hr = True
Exit For
End If
Next t
If Not hr Then
i = i + 1
End If
Loop While i < 5
Debug.Print n(1) & n(2) & n(3) & n(4)
End Sub
答案 1 :(得分:0)
这是我的实施
Dim sResult As String
Dim iCnt As Integer
Dim iTmp As Integer
iCnt = 0
Do While iCnt < 4
iTmp = Int(10 * Rnd())
If InStr(sResult, CStr(iTmp)) = 0 and not (iCnt = 0 and iTmp = 0) Then
sResult = sResult & CStr(iTmp)
iCnt = iCnt + 1
End If
Loop
Debug.Print sResult
编辑:附加检查第一个号码必须是&gt; 0读完RLH评论后