In the development process, often to generate random numbers, such as the generation of static HTML page, the file name is usually generated by generating a random number of the way, when the order is generated, the order number can also be generated by generating a random number of the method obtained.
In C #, random numbers are generally generated with randomness, which can be arbitrarily specified to produce a random number range. Random associative arrays can produce a number of special ranges of stochastic numbers to meet special needs.
The random number of the specified range is generated with random
1. A random number that produces a specified upper limit (such as generating a random number within 100)
Random ran = new random ();
int n = ran. Next (100);
2. Generate a random number with a specified upper and lower bound (e.g., a random number from 100 to 1000)
Random ran = new random ();
int n = ran. Next (100, 1000);
Create a specified range of random numbers using random associative arrays
In some cases, the random number can only take some special specified values, such as discontinuous numbers or some of the specified words, and so on, only with the random can not meet the requirements, must be in the array to implement. The implementation of the idea is like this: first put these special values into the array, and then the length of the array as the upper limit of the random number, the random number is the array subscript, according to the subscript to get the value of the array.
1. Example One
If a discontinuous random number is to be generated, the code is as follows:
public string Getrandom (string[] arr)
{
Random ran = new random ();
int n = ran. Next (arr. LENGTH-1);
return arr[n];
}
Call Method:
String[] arr = { "+", "60", "" "," "" "," "", "" + ") ;
Getrandom (arr);
2. Example Two
If you want to use the specified word as the random number value, the code implementation is the same as the example, the difference is only the random number of values, so as long as the definition of a word array directly call the above code.
Call Method:
String[] arr = { "red", "green", "Blue", "Orange", "white"};
Getrandom (arr);
The above two methods to produce the specified random number, all through testing, can be based on the actual development needs of flexible selection, the general situation is directly with the random can be.
C # Several methods of taking the random number of the specified range