我正在编写一个程序来证明’生日悖论’.
For i = 0 To (pnum - 1) days(i) = rnd(h:=365) Next
它为1到365之间的每个i(days(i))生成一个随机数,函数是:
Private Function rnd(h As Integer) Dim num As Integer Dim rnum As Random rnum = New Random num = rnum.Next(1,h) Return num End Function
当我在for循环中添加一个断点并手动完成它时,它工作正常,但如果我
只需运行该程序,它就会在每天的每个插槽中放入相同的随机数(I).
有什么想法吗?
数字生成现在正在运行,但在使用断点进行调试时,程序仍然以不同的方式工作.
Public Class Form1 Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click Dim prc As Integer For r As Integer = 1 To 100 Dim pnum As Integer = Val(TextBox1.Text) ''Number of people Dim days(pnum - 1) As Integer Dim rnd As Random = New Random() For i As Integer = 0 To (pnum - 1) days(i) = rnd.Next(365) Next Dim count As Integer = 0 Dim inc As Integer = 0 Do For inc = (count + 1) To (pnum - 1) If count = (pnum - 1) Then Exit For End If If days(count) = days(inc) Then prc += 1 ''Match found Exit Do End If Next If count = (pnum - 1) Then Exit Do End If count += 1 Loop Next MsgBox(prc) End Sub End Class
解决方法
这是重写的功能.
Public Shared rnum As New Random 'only one needed per application Private Function myRand(h As Integer) As Integer Dim num As Integer num = rnum.Next(1,h) 'note maxValue is exclusive Return num End Function
从Random的文档中,“默认种子值是从系统时钟派生出来的,并且具有有限的分辨率.因此,通过调用默认构造函数紧密连续创建的不同Random对象将具有相同的默认种子值,并且因此,将生成相同的随机数集……“