Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp classic - VBScript generating same random number when in loop - how to solve?

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...