[英]How to choose a random element from an array in Visual Basic
我創建了一個整數數組,並想從中選擇一個隨機元素。 我怎么做?
YourArray(New Random().Next(0,YourArray.Length-1))
或者為了更清楚而分開:
Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length - 1)
Dim SelectedValue = YourArray(Index)
在0
到Len-1
范圍內生成一個隨機整數,其中Len
是數組的長度。 要生成隨機整數,請使用Random
類的實例。
DIM rand As New Random
DIM idx as rand.Next(0, Len)
REM Now you can pick an element idx from the array
REM to get a random element.
DIM res as myArray(index)
Rnd 可以得到[0,1),那么multiple你的arraylength,你可以得到[0,YourArrayLength)之間的數
Randomize
Int(array.length* Rnd)
Visual Basic 6.0
Dim A() as string
chose = Int(Rnd * UBound(A))
只想說接受的答案是不正確的。
這是正確的
Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length)
Dim SelectedValue = YourArray(Index)
為什么?
因為最大值是獨占的。 因此,例如,如果您不想在 3 個元素中進行選擇,則最大值應該是 3,而不是 2。
'
' Summary:
' Returns a non-negative random integer.
'
' Returns:
' A 32-bit signed integer that is greater than or equal to 0 and less than System.Int32.MaxValue.
Public Overridable Function [Next]() As Integer
'
' Summary:
' Returns a random integer that is within a specified range.
'
' Parameters:
' minValue:
' The inclusive lower bound of the random number returned.
'
' maxValue:
' The **exclusive** upper bound of the random number returned. maxValue must be greater
' than or equal to minValue.
'
' Returns:
' A 32-bit signed integer greater than or equal to minValue and **less than** maxValue;
' that is, the range of return values includes minValue but not maxValue. If minValue
' equals maxValue, minValue is returned.
'
' Exceptions:
' T:System.ArgumentOutOfRangeException:
' minValue is greater than maxValue.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.