C#生成随机数功能示实例

作者:袖梨 2022-06-25

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

 

 代码如下复制代码

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

namespacecsharp

{

  classProgram

  {

    staticvoidMain(string[] args)

    {

      Console.WriteLine("生成随机数n");

      intrandCount = 9;//随机数发的个数

      intrandMin = 1;//随机数最小值

      intrandMax = 21;//随机数最大值

      intrandIndex, flag, temp;

      randIndex = temp = flag = 0;

      Random rand =newRandom();

      int[] randArr =newint[randCount];

      randArr[0] = rand.Next(randMin, randMax);

      while(true)

      {

        flag = 0;

        temp = rand.Next(randMin, randMax);

        for(inti = 0; i <= randIndex; i++)

        {

          if(temp == randArr[i])

          {

            flag = 1;

            break;

          }

        }

        if(flag == 1)//如果 flag == 1 则有重复的数字生成。

        {

          continue;

        }

        elseif(flag == 0)

        {

          randIndex++;

          randArr[randIndex] = temp;

        }

        if(randIndex >= randCount - 1)//如果达到 randCount 退出循环

        {

          break;

        }

      }

      for(inti = 0; i < randCount; i++)

      {

        Console.WriteLine("arr["+ i +"]="+ randArr[i]);

      }

      Console.WriteLine("n任意键退出。");

      Console.ReadLine();

    }

  }

}

 

生成无重复的随机数

运行结果如下:

相关文章

精彩推荐