rand()产生0-32767的一个随机整数

解决方案 »

  1.   

    Example
    /* RAND.C: This program seeds the random-number generator
     * with the time, then displays 10 random integers.
     */#include <stdlib.h>
    #include <stdio.h>
    #include <time.h>void main( void )
    {
       int i;   /* Seed the random-number generator with current time so that
        * the numbers will be different every time we run.
        */
       srand( (unsigned)time( NULL ) );   /* Display 10 numbers. */
       for( i = 0;   i < 10;i++ )
          printf( "  %6d\n", rand() );
    }//你可以取mouse位置等为种子
      

  2.   

    rand()随机产生0-32767之间的一个整数
      

  3.   

    加上srand( (unsigned)time( NULL ) );
    以后rand()每次产生不同的随机数
      

  4.   

    呵呵,同意cris919的意见,必须要加上srand函数来种随机种子,这样才能保证每次的随机数不同
      

  5.   

    randmize初始化,再用rand,不然每次重来都一样
      

  6.   

    srand也可以。我记得有个随机函数可以限定一个范围的.
    你查一下msdn吧
      

  7.   

    取系统时间加上srand函数,来播种一个随机数。你还可以自己再加上一堆乱七八糟的计算来得到随机数^_^
      

  8.   

    range_Max,range_Min控制随即数的范围
    rand()随机产生0-32767之间的一个整数
    RAND_MAX的值为32767
    如下返回一个double数:
    (range_Max-range_Min)*((double)rand()/(double)RAND_MAX)+range_Min
      

  9.   

    下面这段代码是个例子,产生0--21的所有数字进行任意排列。要求不重复。
       
          const int seq_cnt = 21;
    int a[21],i=0,j=0;


    srand((unsigned)time( NULL ));

    bool existing;
    existing=false; while(i<21)
    {
    a[i] = rand() % seq_cnt;
    existing=false;
    if (i == 0)
    i++;
    else 
    {
    for (j=0; j<i; j++)
    {
    if(a[i] == a[j]) 
    existing=true;
    if(existing)
    break;
    }
    if (!existing) i++;
    }
    }
      

  10.   

    查了一下资料, 发现侯捷的书上的一段程序用"&"来运算,
    如:
    a=rand()&100,就可以生成一个0~100的随机数,但是我试了一下,生成的随机数总是那几个数,重复出现的机会再大了,不知道是怎么回事???
    注:我已经在前面加上了srand()