C rand() is not really random [duplicate]

孤街浪徒 提交于 2020-06-28 05:35:11

问题


I'm working on an application. I'm using:

int rand_num = rand() % 100;

To get a random integer between 0 to 99. Now, let's say I got 41, then restarting my application, it's always 41. Same sequence over and over, means it's not really random.

Any solutions?


回答1:


rand generates a pseudo-random number, yes. But you can set the seed.

srand(time(NULL));
int rand_num = rand() % 100;

Set the seed only once.

Or you can use one of the methods from <random>.




回答2:


You have to randomize the seed by calling srand(...) (usually with time(0)) whenever you start your application. Note that it is a pseudo-random number generator i.e. the values generated by the rand() function are not uniformly distributed.




回答3:


Correct. rand() returns a pseudo-random number. The sequence from a given start is deterministic. You can alter the starting point using srand().




回答4:


Use the following:

#include<time.h>

srand(time(NULL));

It will change the seed of pseudo-random generator.

For more information see this.



来源:https://stackoverflow.com/questions/14849866/c-rand-is-not-really-random

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