Random seed at runtime

前端 未结 3 1308
梦谈多话
梦谈多话 2021-01-05 03:35

How can I generate different random numbers at runtime?

I\'ve tried

srand((unsigned) time(0));

But it seems to get me a random numb

3条回答
  •  情歌与酒
    2021-01-05 03:54

    srand()

    As others have mentioned. srand() seeds the random number generator. This basically means it sets the start point for the sequence of random numbers. Therefore in a real application you want to call it once (usually the first thing you do in main (just after setting the locale)).

    int main()
    {
        srand(time(0));
    
        // STUFF
    }
    

    Now when you need a random number just call rand().

    Unit Tests

    Moving to unit testing. In this situation you don;t really want random numbers. Non deterministic unit tests are a waste of time. If one fails how do you re-produce the result so you can fix it?

    You can still use rand() in the unit tests. But you should initialize it (with srand()) so that the unit tests ALWAYS get the same values when rand() is called. So the test setup should call srand(0) before each test (Or some constant other than 0).

    The reason you need to call it before each test, is so that when you call the unit test framework to run just one test (or one set of tests) they still use the same random numbers.

提交回复
热议问题