C++ Predictable Rand() Output

前端 未结 6 436
陌清茗
陌清茗 2021-01-14 14:57

After noticing that the rand() function produced the same output of 41 each time, I seeded the generator using srand(time(0)). That solved the problem of the recurring outpu

6条回答
  •  余生分开走
    2021-01-14 15:03

    The way rand works is you need to follow two rules:

    1. you must seed it first (srand) and
    2. you don't want to seed it before every call to rand. You are just to seed it once before your entire sequence.

    So to really test it you, your code should look more like this:

    int main()
    {
        srand(time(0));
    
        // Output a sequence of 100 random numbers, each less than 1000
        for ( int i = 0; i < 100; i++ )    
            cout << rand() % 1000 << endl;
    
        return 0;
    }
    

    If the program by necessity only outputs one random number each run and the program runs as often as once per second or more, then time(0) may not be a suitable seed. Perhaps using clock_gettime(3) which will give you something more in the milliseconds.

提交回复
热议问题