VBScript 在循环中生成相同的随机数 - 如何解决? [英] VBScript generating same random number when in loop - how to solve?

查看:24
本文介绍了VBScript 在循环中生成相同的随机数 - 如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个函数,它生成一个随机的 8 个字符长的数字字符串.如果每页调用一次它就可以工作,即如果我刷新它会显示一个新数字.

So I have this function which generates a random string of digits 8 characters long. It works if its called once per page, ie if I refresh it will show a new number.

但我想在循环中生成其中的许多,并返回相同的数字.我该如何解决这个问题?

But I want to generate many of these inside a loop and its returning the same number. How can I solve this?

Function generateCode()

   pChar = "0123456789"

   pCount = Len(pChar) 

   Dim psw
   psw = ""

   Randomize
   For i = 1 To 8 ' password length
      psw = psw & Mid( pChar, 1 + Int(Rnd * pCount), 1 )
   Next

 generateCode= psw
End Function

现在我认为 Randomize 可能基于当前时间,所以我取出 Randomize 行并在调用 generateCode() 的循环之前调用 Randomize 我 - 仍然没有工作!

Now I thought Randomize may be based off the current time, so I took the Randomize line out and called Randomize before the loop that calls generateCode() i- still didn't work!

推荐答案

Randomize 不带任何参数使用系统时间为伪随机数生成器提供种子.如果您非常快地多次调用它,系统时间将不会改变,因此您每次都将使用相同的种子重新初始化 PRNG,并提供相同的随机数.

Randomize without any arguments seeds the pseudo-random number generator using the system time. If you call it multiple times very quickly the system time won't have changed so you will reinitialize the PRNG with the same seed each time, giving the same random numbers.

您应该在页面上只调用一次 Randomize,而不是多次.

You should only call Randomize only once on your page, not multiple times.

这篇关于VBScript 在循环中生成相同的随机数 - 如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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