Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

vb.net - Call to Rnd() generating the same number

When I set up this bit of code, every time I debug the software it generates the same number. Can anyone tell me why this is happening?

dim value as integer
value = (CInt(Int(100 * Rnd())))
messagebox.show(value)

Because it should be random. here is an example: (From top to bottom)

  • I debug the software
  • the code runs, and it generates the number 70
  • I stop the debugging
  • I debug it again and it generates the number 70 again

And that's happening over and over, the first two times I thought it was just luck, but when I did it a couple of times it always came back on the 70 (as an example).

But when I keep the software running and I run the code over and over again, by the use of a button, it generates completely different, and random numbers. Start it back up again and there is the number 70 again.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You need to call

Randomize()

Before you call Rnd() to initialize your random num ber generator. If you don't, every time that you run the program you will get the same sequence of numbers.

Example:

dim value as integer
Randomize()
value = (CInt(Int(100 * Rnd())))
messagebox.show(value)

The reason is that the Rnd() will always use the same seed to start the sequence. If you want to read more about it, is very well explained explained here: https://msdn.microsoft.com/en-us/library/8zedbtdt(v=vs.90).aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...