Generate random number

  • Thread starter Thread starter Luigi
  • Start date Start date
L

Luigi

Hi all
How can I create a method that returns me a random number between 1 and 20
(extreme included)?

Thanks in advance.

Luigi
 
Luigi said:
Hi all
How can I create a method that returns me a random number between 1 and 20
(extreme included)?

Thanks in advance.


Random rand = new Random();
int num = rand.Next(1,20);

Dubravko
 
* Luigi wrote, On 15-1-2010 10:28:
Hi all
How can I create a method that returns me a random number between 1 and 20
(extreme included)?

Thanks in advance.

Luigi

See thee Random class.
 
Luigi said:
Hi all
How can I create a method that returns me a random number between 1 and 20
(extreme included)?

As has been mentioned, you will want to use the Random class. However,
something very important you need to keep in mind: presumably you may
want to choose this random number more than once. If so, you MUST
create a single instance of Random, and reuse it each time you want a
new random number.

If you keep creating new Random instances each time you want a new
random number, you have a very good chance of having several instances
in a row initialized identically, and thus return an identical number.

Pete
 
Tom Shelton said:
Actually, if you want the extreme as you mentioned in your original post, that
would be:

int num = rand.Next(1, 21);

Do not create a new instance of Random on each call to the function. This
defeats the randomness of the algorithm. Set the instance of Random in the
constructor.

Mike
 
Back
Top