|
@@ -0,0 +1,40 @@
|
|
1
|
+> Random()随机函数
|
|
2
|
+
|
|
3
|
+```
|
|
4
|
+ Random ran=new Random();
|
|
5
|
+ int RandKey=ran.Next(100,999);
|
|
6
|
+```
|
|
7
|
+> 使用两种方式初始化一个随机数发生器
|
|
8
|
+- 第一种方法不指定随机种子,系统自动选取当前时间作为随机种子:
|
|
9
|
+ Random ro = new Random();
|
|
10
|
+- 第二种方法可以指定一个int型参数作为随机种子:
|
|
11
|
+```
|
|
12
|
+ int iSeed=10;
|
|
13
|
+ Random ro = new Random(10);
|
|
14
|
+ long tick = DateTime.Now.Ticks;
|
|
15
|
+ Random ran = new Random((int)(tick & 0xffffffffL) | (int) (tick >> 32));
|
|
16
|
+```
|
|
17
|
+```
|
|
18
|
+用随机数实现一件事情出现的概率是10%,另一件事情出现的概率是90%
|
|
19
|
+
|
|
20
|
+private staticvoidMain(string[] args)
|
|
21
|
+{
|
|
22
|
+ Random ran =
|
|
23
|
+newRandom(unchecked((int)DateTime.Now.Ticks));
|
|
24
|
+int num1 = 0;
|
|
25
|
+int num2 = 0;
|
|
26
|
+for (inti = 0; i<100000; i++)
|
|
27
|
+{
|
|
28
|
+ int n = ran.Next(0, 10);
|
|
29
|
+ if (n == 0)
|
|
30
|
+ {
|
|
31
|
+ num++;
|
|
32
|
+ }
|
|
33
|
+ else
|
|
34
|
+ {
|
|
35
|
+ num2++;
|
|
36
|
+ }
|
|
37
|
+}
|
|
38
|
+Console.Write(num1 + "--" + num2);
|
|
39
|
+}
|
|
40
|
+```
|