2个回答
展开全部
思路...
1.准备一个数组,你要生成多少个随机数,下标就弄多少
2.为数组赋值
3.遍历数组,每次生成一个随机数,然后根据随机数将数组内的元素对调,达到打乱顺序的目的
4.经过2,3步,数组内的数字就是你要的不重复的随机数了...
这样做的好处是效率高,就算你用这个代码来生成1万个不重复的数字也是很快的,因为我们只是随机打乱顺序而已,所以保证原有的数字不会重复,如果写代码滤重,效率就低了
Private Sub Form_Load()
Dim a(3) As Long
Dim i As Long, tmp As Long, tmpIndex As Long
'给数组赋值0-3
For i = 0 To 3
a(i) = i
Next
'打乱数组顺序
For i = 0 To 3
'随机生成0-3
tmpIndex = Rnd * 4
'调换数组内数字的位置
tmp = a(tmpIndex)
a(tmpIndex) = a(i)
a(i) = tmp
Next
'输出
Text1.Text = a(0)
Text2.Text = a(1)
Text3.Text = a(2)
Text4.Text = a(3)
End Sub
1.准备一个数组,你要生成多少个随机数,下标就弄多少
2.为数组赋值
3.遍历数组,每次生成一个随机数,然后根据随机数将数组内的元素对调,达到打乱顺序的目的
4.经过2,3步,数组内的数字就是你要的不重复的随机数了...
这样做的好处是效率高,就算你用这个代码来生成1万个不重复的数字也是很快的,因为我们只是随机打乱顺序而已,所以保证原有的数字不会重复,如果写代码滤重,效率就低了
Private Sub Form_Load()
Dim a(3) As Long
Dim i As Long, tmp As Long, tmpIndex As Long
'给数组赋值0-3
For i = 0 To 3
a(i) = i
Next
'打乱数组顺序
For i = 0 To 3
'随机生成0-3
tmpIndex = Rnd * 4
'调换数组内数字的位置
tmp = a(tmpIndex)
a(tmpIndex) = a(i)
a(i) = tmp
Next
'输出
Text1.Text = a(0)
Text2.Text = a(1)
Text3.Text = a(2)
Text4.Text = a(3)
End Sub
展开全部
我写的很丑陋…… 期待更好的办法。
txt(0),txt(1),txt(2),txt(3)是那四个文本框
Private Sub Form_Click()
txt(0).Text = GetRand
txt(1).Text = GetRand
While txt(1).Text = txt(0).Text
txt(1).Text = GetRand
Wend
txt(2).Text = GetRand
While txt(2).Text = txt(0).Text Or txt(2).Text = txt(1).Text
txt(2).Text = GetRand
Wend
txt(3).Text = GetRand
While txt(3).Text = txt(2).Text Or txt(3).Text = txt(1).Text Or txt(3).Text = txt(0).Text
txt(3).Text = GetRand
Wend
End Sub
Private Function GetRand() As Integer
Randomize (Time)
GetRand = Rnd() * 10000 Mod 4
End Function
txt(0),txt(1),txt(2),txt(3)是那四个文本框
Private Sub Form_Click()
txt(0).Text = GetRand
txt(1).Text = GetRand
While txt(1).Text = txt(0).Text
txt(1).Text = GetRand
Wend
txt(2).Text = GetRand
While txt(2).Text = txt(0).Text Or txt(2).Text = txt(1).Text
txt(2).Text = GetRand
Wend
txt(3).Text = GetRand
While txt(3).Text = txt(2).Text Or txt(3).Text = txt(1).Text Or txt(3).Text = txt(0).Text
txt(3).Text = GetRand
Wend
End Sub
Private Function GetRand() As Integer
Randomize (Time)
GetRand = Rnd() * 10000 Mod 4
End Function
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询