How often should I call srand() in a C++ application?

大城市里の小女人 提交于 2019-11-26 17:23:23

问题


I have a C++ application which calls rand() in various places. Do I need to initialize srand() regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?


回答1:


If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand at all, but rather something threadsafe like drand48_r, which lets you maintain a per-thread state (so you can seed once per thread).




回答2:


Only once, at the start of your application.




回答3:


No just calling once is fine. Use the seed value to make the random sequence the same on each execution. This could be useful in making (for example) a game's behaviour deterministic when you replay it for debugging.




回答4:


call it once when the app starts



来源:https://stackoverflow.com/questions/6954490/how-often-should-i-call-srand-in-a-c-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!