use of srand() in c++

后端 未结 2 1927
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 08:44

I am new to c++ so this doubt might look basic but I am not getting the difference between rand() and srand() and what do u mean by \"seed\" in srand()? when I write srand(t

2条回答
  •  遥遥无期
    2020-12-05 09:20

    rand() doesn't produce a random number - it uses some quite easy formula to compute the next "random value" based on its stored internal state that changes each time a random value is generated. srand() sets that internal state.

    This way you can get reproduceable sets of numbers - you call srand() with a given value and rand() then produces a set of values. When you start the program next time and call srand() with exact same value rand() will produce exactly the same set of values. This is useful for simulation.

    Calling srand( time( NULL ) ) makes your program generate a set of values that will depend on the current time and therefore be irreproduceable - each time you restart a program a new set of numbers is generated.

提交回复
热议问题