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

Tags: C/C++

Feedback in SANSUIZ | 留言单

License (CC) BY-NC-SA | Subscribe RSS | Email xmann_zh@foxmail.com | Back Top 🫠 |
已有位小伙伴到此一游