VB随机函数两次返回相同的值 [英] VB random function returns same value twice

查看:41
本文介绍了VB随机函数两次返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dim top = RandomPosition()
Dim left = RandomPosition()    
End Sub

Function RandomPosition()
    Dim rand As New Random()
    Dim number = rand.Next(1, 100)
    Return number
End Function

大家好,我正在尝试获取 2 个不同的随机值(目前.一旦成功,我将需要更多).问题是上面的代码 topleft 总是等于相同的随机数.

Hi guys I am trying to get 2 different random values (for now. Once this works I will need a few more). The problem is that with the above code top and left always equal the same random number.

推荐答案

您每次调用 RandomPosition 时都会创建一个 随机序列,但是,因为您正在调用它很快,他们将拥有相同的种子(基于时间).相同的种子意味着相同的序列.

You create a new random sequence every time you call RandomPosition but, because you're calling it in quick succession, they'll have the same seed (based on time). Same seed means same sequence.

您应该创建一次 rand 变量,然后继续使用它,例如:

You should create the rand variable once, then just continue to use it, something like:

Dim rand as New Random()
Dim top = rand.Next (1, 100)
Dim left = rand.Next (1, 100)

或者,如果您真的希望在它自己的函数中使用它,请将随机生成器设为静态,以便它在调用之间保持其状态:

Alternatively, if you really want it in its own function, make the random generator static so that it maintains its state across calls:

Function RandomPosition()
    Static rand = New Random()
    Return rand.Next(1, 100)
End Function

以下完整的 VB2010 程序显示了这一点:

The following complete VB2010 program shows this in action:

Module Module1
    Function RandomPosition()
        Static rand As Random = New Random()
        Return rand.Next(1, 100)
    End Function

    Sub Main()
        Dim top = RandomPosition()
        Dim left = RandomPosition()
        MsgBox("top = " & CStr(top) & ", left = " & CStr(left))
    End Sub
End Module

它在各种运行中输出:

top = 7, left = 93
top = 45, left = 90
top = 44, left = 62

这篇关于VB随机函数两次返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆