Generate random number

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
 
D

Dubravko Sever

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
 
J

Jesse Houwing

* 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.
 
P

Peter Duniho

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
 
F

Family Tree Mike

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top