好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#生成随机数功能示例

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

?

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#程序设计有所帮助。

dy("nrwz");

查看更多关于C#生成随机数功能示例的详细内容...

  阅读:52次