Thursday, July 22, 2010

Generating Random Numbers - C#

Random numbers can be used in many ways. They can determine random events in game, pick a winner out of a list of contestants, or used to simulate a coin flip. Using random numbers is very simple in C#.

First you must declare an instance of the Random class.
Random ran = new Random();

The Random class has the following methods:

Next() - Returns a nonnegative random integer.
Next(int) - Returns a nonnegative random number below the value of int.
Next(int1, int2) - Returns a nonnegative random number that is at least int1, but less than int2
NextBytes() - Fills an array of bytes with random, nonnegative integers.
NextDouble() - Returns a random number between 0.0 and 1.0

Here is an example using random numbers. The following program generates a random number between 0-10 and prints results.
Random ran = new Random();

int result = ran.Next(0, 10); //number is at least 0, but less than 10

if(result >=5)
   Console.WriteLine("You Generated a BIG Number!");
else
   Console.WriteLine("You Generated a small Number :(");

0 comments:

Post a Comment