C/C++：Test srand() function

Nov 21, 2015

`srand(unsigned int seed)` takes in `seed` and initialize a series of random values which can be obtained by a series of `rand()` functions.

For a certain value of seed, the generalized series of random values is always the same. For example, `srand(1)` always generalize 6334 18467 41 …

Without initialization argument of `srand()`, the random series obtained by `rand()` is the same to those generalized with `srand(1)`.

Therefore, to generalize a different random values every time, we obtain the system clock to be the seed: `srand((unsigned int)time(0))`.

Code used for this test (running in Visual Studio 2013):

``````#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <Windows.h>

/*
Date: 2015-10-22
*/

/*
Test result:

srand(unsigned int seed) takes in seed and initialize a series of random values
which can be obtained by a series of rand() functions;

For a certain value of seed,  the generalized series of random values is always the same.
For example, srand(1) always generalize 6334 18467 41 ...

Without initialization argument of srand(), the random series obtained by rand()
is the same to those generalized with srand(1).

Therefore, to generalize a different random values every time, we obtain the
system clock to be the seed: srand((unsigned int)time(0)).
*/

void func()
{
std::cout << rand() << " " << rand() << " " << rand() << std:: endl;
}

int main()
{
//srand((unsigned int)time(0));
srand(2);
std::cout << time(0) << std::endl;

std::cout << rand() << " " << rand() << " " << rand() << std::endl;

std::cout << rand() << " " << rand() << " " << rand() << std::endl;

Sleep(100);

t1.join();
t2.join();

std::cout << rand() << " " << rand() << " " << rand() << std::endl;
//srand((unsigned int)time(0));

std::cout << rand() << " " << rand() << " " << rand() << std::endl;
std::cout << rand() << " " << rand() << " " << rand() << std::endl;

getchar();
return 0;
}
``````

Tags: C/C++

Comment by Github Issues

Chat in Gitter/fan-farm