gpt4 book ai didi

vb.net - 为什么这个随机数生成代码不起作用?

转载 作者:行者123 更新时间:2023-12-01 09:56:43 25 4
gpt4 key购买 nike

我正在编写一个程序来证明“生日悖论”。

    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

这就是全部代码。它所做的是从集合中搜索两个匹配的随机数。整个过程重复 100 次,它应该计算结果,但它只输出 0 或 100。

最佳答案

这里是重写的函数。

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 对象将具有相同的默认种子值,因此将产生相同的随机数集 ..."

这就是您遇到问题的原因。我还更改了函数的名称,因为它与旧的 Rnd 方法匹配。

关于vb.net - 为什么这个随机数生成代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25105640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com