Translations of this page?:

rand

语法:

    #include <cstdlib>
    int rand( void );

函数rand()返回一个0到RAND_MAX的整型。 一个例子:

     srand( time(NULL) );
     for( i = 0; i < 10; i++ )
       printf( "Random number #%d: %d\n", i, rand() );

注意: 不要用“% (模数)”去限制随机数生成。随机性很大程度上被降低了。相反应使用这个算法来生成0和上限之间适当分布的随机数:

    // 注意浮点数很重要,否则整数可能在加上1后溢出
    int randomNumber(int hi)  //the correct random number generator for [0,hi-1]
    {
       // scale in range [0,1)
       const float scale = rand()/float(RAND_MAX);
 
       // return range [0..hi-1]
       return int(scale*hi); // implicit cast and truncation in return
    }

相关主题: srand

 
• • • SitemapRecent changesRSScc