Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random int number?

Tags:

c#

random

How do I generate a random integer in C#?

like image 869
Rella Avatar asked Apr 24 '10 23:04

Rella


People also ask

What is the formula to generate random numbers?

If we wish to generate a random number between two numbers, we can use the formula: RAND() * (b – a) + a, where a is the smallest number and b is the largest number that we wish to generate a random number for.

How do you randomly generate an int in C++?

rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.


1 Answers

The Random class is used to create random numbers. (Pseudo-random that is of course.).

Example:

Random rnd = new Random(); int month  = rnd.Next(1, 13);  // creates a number between 1 and 12 int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6 int card   = rnd.Next(52);     // creates a number between 0 and 51 

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

like image 151
Guffa Avatar answered Sep 17 '22 13:09

Guffa