How do you create 2 random values [modified]
-
I wrote
Random RollOne = new Random(); Random RollTwo = new Random(); dieOne = RollOne.Next(1, 7); dieTwo = RollTwo.Next(1 , 7); sum = dieOne + dieTwo;
but dieOne and dieTwo are always equal, how do you make two independent random values? Edit: Thanks Mikanu, it works now.
modified on Monday, July 13, 2009 10:43 PM
-
I wrote
Random RollOne = new Random(); Random RollTwo = new Random(); dieOne = RollOne.Next(1, 7); dieTwo = RollTwo.Next(1 , 7); sum = dieOne + dieTwo;
but dieOne and dieTwo are always equal, how do you make two independent random values? Edit: Thanks Mikanu, it works now.
modified on Monday, July 13, 2009 10:43 PM
The correct way to do that is to create an instance of the Random class and then call one of the following methods: -
Next(Int32 max) // will return a random number smaller than _max_
-NextByte() // will return a random byte (between 0 and 255)
-NextDouble() // will return a random number between 0.0 and 1.0
Here's a code sample which will generate two random numbers, a and b, between 0 and 10Random rnd = new Random();
int a = rnd.Next(10);
int b = rng.Next(10);---- <a href="www.mdinescu.com">www.mdinescu.com</a>
-
I wrote
Random RollOne = new Random(); Random RollTwo = new Random(); dieOne = RollOne.Next(1, 7); dieTwo = RollTwo.Next(1 , 7); sum = dieOne + dieTwo;
but dieOne and dieTwo are always equal, how do you make two independent random values? Edit: Thanks Mikanu, it works now.
modified on Monday, July 13, 2009 10:43 PM
To add to the other post ( which was correct ), there is no such thing as a random number to a computer. It only looks that way. A random sequence is started by what's called a seed value. You can specify a seed value to regenerate the same pseudo random sequence if you need to. If you don't specify one, the current date and time are used. As you can see, you created two random objects with the same seed, so they will both start on the same number.
Christian Graus Driven to the arms of OSX by Vista. Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
-
I wrote
Random RollOne = new Random(); Random RollTwo = new Random(); dieOne = RollOne.Next(1, 7); dieTwo = RollTwo.Next(1 , 7); sum = dieOne + dieTwo;
but dieOne and dieTwo are always equal, how do you make two independent random values? Edit: Thanks Mikanu, it works now.
modified on Monday, July 13, 2009 10:43 PM
You should create one instance of Random as a static field of the class and use it whenever you need it. It should never be a local variable of a method.