How to generate and use random numbers with c sharp?
Posted On : Aug 20, 2020
The Random class with its Next and NextDouble functions can be used for this. The Next function generates int (integer) type of numbers while NextDouble generates numbers between 0 and 1 in decimal. NextDouble function takes no parameters but Next function takes two parameters as minimum and maximum numbers. If only one parameter specified, minimum number will be considered as 0 and entered number will be considered as maximum value. The minimum value is included in the random numbers to be generated, while the biggest number to be generated is always 1 less than the maximum value entered.
// Declare an integer variable to be assigned random number to it later.
int myinteger = 0;
// Declare a new variable called "generate_random" from Random class.
Random generate_random = new Random();
// Assign the random integer which generated between 0 and 101 (minimum is 0, maximum is 100) into the variable called "myinteger".
myinteger = generate_random.Next(0, 101);
// Example output value : 19
double mydoublenumber = 0;
Random generate_double = new Random();
mydoublenumber = generate_double.NextDouble();
// Example output value : 0,330423261192824
// To decrease the decimal count, ("0.##") format of toString() function can be used.
mydoublenumber.toString("0.##");
// Example output value : 0,33
mydoublenumber.toString("0.####");
// Example output value : 0,3304
