What‘s the difference between srand(1) and srand(0)

后端 未结 7 2191
广开言路
广开言路 2020-12-30 02:23

I just found out the hard way that srand(1) resets the PRNG of C(++) to the state before any call to srand (as defined in the reference). However,

7条回答
  •  自闭症患者
    2020-12-30 03:19

    It is probably an implementation detail. The standard mandates that the random seed 1 is special, and the internal register of your specific random generator algorithm is probably zero-initialized, thus causing the same random sequence for seed(0) and seed(1). I'd even wager that the first line of your srand() implementation looks like:

    if ( seed == 1 ) seed = 0;
    

    to force standard-conformant behaviour.

    Generally, the random number generators for rand() and srand() are not required to give different sequences for different seeds, but the same sequence for the same seed. So, don't rely on different seeds generating different random sequences, and you should be fine. If not, welcome to implementation-specific fun.

提交回复
热议问题