I was just wondering how the random number generator in C# works. I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
You can use Random.Next(int maxValue)
:
Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.
var r = new Random(); // print random integer >= 0 and < 100 Console.WriteLine(r.Next(100));
For this case however you could use Random.Next(int minValue, int maxValue)
, like this:
// print random integer >= 1 and < 101 Console.WriteLine(r.Next(1, 101);) // or perhaps (if you have this specific case) Console.WriteLine(r.Next(100) + 1);
I was just wondering how the random number generator in C# works.
That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.
I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
You can use Random.Next(int, int)
:
Random rng = new Random(); for (int i = 0; i < 10; i++) { Console.WriteLine(rng.Next(1, 101)); }
Note that the upper bound is exclusive - which is why I've used 101 here.
You should also be aware of some of the "gotchas" associated with Random
- in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With