window下的RAND_MAX为:0x7fff=2^15-1=32767
linxu下的RAND_MAX为:2^31-1=2147483647
不妨,就Windows下进行说明:
Rand函数返回返回值是0到RAND_MAX(32767) 范围内的一个(伪)随机整数。
取指定区间的(伪)随机数不建议采用“模除+加法”的方式,
譬如:如果采用此法去0-10000内的随机数,则写法为
srand((unsigned)time( NULL ));
int n = rand()%10000;
则0-2767之间每个数出现的概率为4/32676,而2768-9999之间的书出现的概率为3/32676,和前者是不同的。不过rand()产生的是伪随机数了这个无关紧要,哈哈哈 。
建议采用如下方式:
int u =(double)rand()/(RAND_MAX +1)*(range_max - range_min)+ range_min
一下是VS开发文档示例:
// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//
#include
#include
#include
voidSimpleRandDemo(int n )
{
// Print n random numbers.
int i;
for( i =0; i < n; i++)
printf(" %6d\n", rand());
}
voidRangedRandDemo(int range_min,int range_max,int n )
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for( i =0; i < n; i++)
{
int u =(double)rand()/(RAND_MAX +1)*(range_max - range_min)
+ range_min;
printf(" %6d\n", u);
}
}
int main(void)
{
// Seed the random-number generator with the current time so that
// the numbers will be different every time we run.
srand((unsigned)time( NULL ));
SimpleRandDemo(10);
printf("\n");
RangedRandDemo(-100,100,10);
}
/***********************************分割线*****************************************/
建议使用random库生成真随机数,如下:
#include
#include
usingnamespace std;
int main()
{
random_device rd; // non-deterministic generator
mt19937 gen(rd()); // to seed mersenne twister.
uniform_int_distribution<> dist(1,6);// distribute results between 1 and 6 inclusive.
for(int i =0; i <5;++i){
cout << dist(gen)<<" ";// pass the generator to the distribution.
}
cout << endl;
}
输出如下:
51612