Title here
Summary here
The Random
class in C# provides pseudorandom number generation.
using System;
class RandomNumbers
{
static void Main()
{
// Create a new instance of Random
Random random = new Random();
// Next(int) returns a random integer that is less than the specified maximum
Console.Write(random.Next(100) + ",");
Console.WriteLine(random.Next(100));
// NextDouble() returns a random floating-point number between 0.0 and 1.0
Console.WriteLine(random.NextDouble());
// This can be used to generate random floats in other ranges, for example 5.0 <= f' < 10.0
Console.Write((random.NextDouble() * 5) + 5 + ",");
Console.WriteLine((random.NextDouble() * 5) + 5);
// If you want a known seed, create a new Random instance with a specific seed
Random random2 = new Random(42);
Console.Write(random2.Next(100) + ",");
Console.WriteLine(random2.Next(100));
// Using the same seed will produce the same sequence of random numbers
Random random3 = new Random(42);
Console.Write(random3.Next(100) + ",");
Console.WriteLine(random3.Next(100));
}
}
To run the program, compile and execute it:
$ csc RandomNumbers.cs
$ mono RandomNumbers.exe
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49
Note that some of the generated numbers may be different when you run the sample, except for the ones generated with a specific seed.
See the Random Class documentation for references on other random quantities that C# can provide.