C/C++:Test srand() function

2015-11-21

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 <thread>
#include <Windows.h>

/*
    Author: ZHENG Fan fzheng@link.cuhk.edu.hk
    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 << "Enter thread " << std::this_thread::get_id() << std::endl;
    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;

    std::thread t1(func);

    Sleep(100);

    std::thread t2(func);

    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;
}

标签: C/C++

留言请移步 SANSUIZ | 兔小巢

授权协议 (CC) BY-NC-SA | 订阅 RSS | 邮箱 sansui_z@126.com