生成不重复随机数的VB代码
时间: 2024-04-09 10:10:00 浏览: 84
VB生成不重复的随机数
5星 · 资源好评率100%
以下是VB代码,可以生成指定范围内不重复的随机数:
```
Private Function GenerateRandomNumbers(ByVal min As Integer, ByVal max As Integer, ByVal count As Integer) As Integer()
'初始化数组
Dim numbers(count - 1) As Integer
'填充数组
For i As Integer = 0 To count - 1
numbers(i) = i + min
Next
'随机交换数组元素
Dim rand As New Random()
For i As Integer = 0 To count - 1
Dim j As Integer = rand.Next(i, count)
Dim temp As Integer = numbers(i)
numbers(i) = numbers(j)
numbers(j) = temp
Next
'截取数组
Dim result(count - 1) As Integer
Array.Copy(numbers, result, count)
'返回结果
Return result
End Function
```
使用方法如下:
```
Dim numbers() As Integer = GenerateRandomNumbers(1, 100, 10)
```
其中,第一个参数指定随机数范围的最小值,第二个参数指定随机数范围的最大值,第三个参数指定随机数的个数。函数返回一个整数数组,包含指定个数的不重复随机数。
阅读全文