|
12345678910111213141516171819202122232425262728293031323334353637383940 |
- > Random()随机函数
-
- ```
- Random ran=new Random();
- int RandKey=ran.Next(100,999);
- ```
- > 使用两种方式初始化一个随机数发生器
- - 第一种方法不指定随机种子,系统自动选取当前时间作为随机种子:
- Random ro = new Random();
- - 第二种方法可以指定一个int型参数作为随机种子:
- ```
- int iSeed=10;
- Random ro = new Random(10);
- long tick = DateTime.Now.Ticks;
- Random ran = new Random((int)(tick & 0xffffffffL) | (int) (tick >> 32));
- ```
- ```
- 用随机数实现一件事情出现的概率是10%,另一件事情出现的概率是90%
-
- private staticvoidMain(string[] args)
- {
- Random ran =
- newRandom(unchecked((int)DateTime.Now.Ticks));
- int num1 = 0;
- int num2 = 0;
- for (inti = 0; i<100000; i++)
- {
- int n = ran.Next(0, 10);
- if (n == 0)
- {
- num++;
- }
- else
- {
- num2++;
- }
- }
- Console.Write(num1 + "--" + num2);
- }
- ```
|