从一组数字中选择一个随机数

时间:2009-10-28 00:23:22

标签: vb.net arrays

我有一个像这样的整数数组; dim x as integer()= {10,9,4,7,6,8,3}。 现在我想从中选择一个随机数,我怎样才能在visual basic中做到这一点?提前感谢...

2 个答案:

答案 0 :(得分:3)

首先你需要一个随机发生器:

Dim rnd As New Random()

然后你选择一个代表数组索引的随机数:

Dim index As Integer = rnd.Next(0, x.Length)

然后从数组中获取值:

Dim value As Integer = x(index)

或者最后两个作为单一陈述:

Dim value As Integer = x(rnd.Next(0, x.Length))

现在,如果您还想删除从数组中选择的数字,则不应首先使用数组。您应该使用List(Of Integer),因为它的大小是动态的。

答案 1 :(得分:0)

从数组中随机选择0到length-1的索引。

相关问题