VB怎样 随机提取10个数中的5个数存到数组中

2024-11-26 13:44:14
推荐回答(2个)
回答1:

先将这10个数字放在一个数组a(10)中。然后通过随机函数的调用来随机抽取数字。每次抽取一个,若抽取到的数字已被抽取,则进行下一次抽取。这大概就是基本想法吧。
通过代码实现:
Dim a(10) As Integer '存放要抽取的数字。
Dim Fir(5) As Integer '存放抽取到的5个数字的下标,最后改为存该下标的数字。
Dim sec(5) As Integer '存放未被抽取到的5个数字的下标,后改为存数字。
'假设a数组已经赋值,这就不再多写
(手机写的,字数有限制)

回答2:

Dim x(9) As Integer, a(4) As Integer, b(4) As IntegerDim c(9) As BooleanDim i As Integer, n As Integer, m As IntegerFor i = 1 To 10x(i - 1) = iNexti = 0 Do Until i >= 5Don = Int(Rnd() * 10)Loop Until Not c(n)c(n) = Truei = i + 1Loopm = 0
n = 0For i = 0 To 9If c(i) Thena(m) = x(i)m = m + 1Elseb(n) = x(i)n = n + 1End IfNext'输出看一下。Debug.Print "a:";
For i = 0 To 4
Debug.Print a(i);
Next
Debug.Print ""
Debug.Print "b:";
For i = 0 To 4
Debug.Print b(i);
Next