C#生成随机数功能示例

时间:2022-02-13 14:50:02

本文实例讲述了c#生成随机数功能。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace csharp
{
  class program
  {
    static void main(string[] args)
    {
      console.writeline("生成随机数\n");
      int randcount = 9;//随机数发的个数
      int randmin = 1;//随机数最小值
      int randmax = 21;//随机数最大值
      int randindex, flag, temp;
      randindex = temp = flag = 0;
      random rand = new random();
      int[] randarr = new int[randcount];
      randarr[0] = rand.next(randmin, randmax);
      while (true)
      {
        flag = 0;
        temp = rand.next(randmin, randmax);
        for (int i = 0; i <= randindex; i++)
        {
          if (temp == randarr[i])
          {
            flag = 1;
            break;
          }
        }
        if (flag == 1)//如果 flag == 1 则有重复的数字生成。
        {
          continue;
        }
        else if (flag == 0)
        {
          randindex++;
          randarr[randindex] = temp;
        }
        if (randindex >= randcount - 1)//如果达到 randcount 退出循环
        {
          break;
        }
      }
      for (int i = 0; i < randcount; i++)
      {
        console.writeline("arr[" + i + "]=" + randarr[i]);
      }
      console.writeline("\n任意键退出。");
      console.readline();
    }
  }
}

生成无重复的随机数

运行结果如下:

C#生成随机数功能示例

希望本文所述对大家c#程序设计有所帮助。