本文共 1424 字,大约阅读时间需要 4 分钟。
srand((unsigned)time(NULL))是初始化随机函数种子:
1、是拿当前系统时间作为种子,由于时间是变化的,种子变化,可以产生不相同的随机数。
计算机中的随机数实际上都不是真正的随机数,如果两次给的种子一样,是会生成同样的随机序列的。 所以,一般都会以当前的时间作为种子来生成随机数,这样更加的随机。
2、使用时,参数可以是unsigned型的任意数据,比如srand(10); 3、如果不使用srand,用rand()产生的随机数,在多次运行,结果是一样的。
void test_rand(void)
{ unsigned long n; srand((unsigned)time(NULL)); for(int i = 0; i < 100; i++) { n = rand(); printf("d\n", n); }}
int rand (void); Generate random number Returns a pseudo-random integral number in the range between 0 and .This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function . is a constant defined in . A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range: 123 v1 = rand() % 100; // v1 in the range 0 to 99v2 = rand() % 100 + 1; // v2 in the range 1 to 100v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely)
转载地址:http://evxgi.baihongyu.com/