1.

Solve : C# Help with Random Command.?

Answer»

I WENT to msdn.com to find a command that would pick a random number for a project I'm working on, but when I read through the command methods It confused me... all I want it to do is pick a random number from 1 - 12 so it's like rolling dice.

Can I have some help? A random number generator must always be initialized with a seed.  From then on the number is generated based upon a mathematical FORMULA using the seed value and successive values.  In C# you have two constructs for the Random class.  The first one has no arguments and uses a time value (always different) for a seed.  The second one allows you to specify an int value as a seed.  Easiest to use the first.  Next you retrieve the random number.  In this case the number will be between 0.0 and 1.0.  This means you've got to scale your number from there, so...

        float obj = new Random();
        int random_value = (int) ((obj.Sample() * 11) + 1);

This was not tested but should fly.Ok I'll try it thank you!
(EDIT)
Nope didn't work for me thank you for trying.Ooops.  It's simpler than I first explained...

Random rand = new Random();
int random_value = rand.Next(1,12);

That's it.  Instantiate "rand" only once but execute "rand.Next(1,12)" over and over...Ok I'll try this out thank you for correcting it. 
(EDIT)
YAY IT WORKS!!! Thank you Thank you Thank you! (I really NEEDED this!)
And now I understand the random command too.



Discussion

No Comment Found