C++ Predictable Rand() Output

前端 未结 6 434
陌清茗
陌清茗 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:18

    I recently ran across the same problem and found that Karoly Horvath's comment on your original question solved the issue, although it is a bit "hacky". I was seeing a predictable increase in return values, and after sticking another rand() immediately after the srand(), the problem went away. I ended up with this:

    srand(time(NULL));
    rand();
    int seed = rand();
    

    I'd like to figure out why this is happening...but in the meantime this works.

提交回复
热议问题