我明白,使用srand(time(0))有助于设置随机种子.但是,以下代码为两个不同的列表存储相同的数字集.
想知道,当多次调用以下函数时,如何生成不同的数字集.
void storeRandomNos(std::list<int>& dataToStore)
{
int noofElements = 0;
srand(time(0));
noofElements = (rand() % 14 ) + 1;
while ( noofElements --)
{
dataToStore.push_back(rand() % 20 + 1 );
}
}
Run Code Online (Sandbox Code Playgroud)
这是代码的其余部分.
void printList(const std::list<int>& dataElements, const char* msg);
void storeRandomNos(std::list<int>& dataToStore);
int main()
{
std::list<int> numberColl1;
std::list<int> numberColl2;
storeRandomNos(numberColl1);
storeRandomNos(numberColl2);
printList(numberColl1 , "List1");
printList(numberColl2 , "Second list");
}
void printList(const std::list<int>& dataElements, const char* msg)
{
std::cout << msg << std::endl;
std::list<int>::const_iterator curLoc = dataElements.begin();
for ( ; curLoc != dataElements.end() ; ++curLoc)
{
std::cout << *curLoc << ' ';
}
}
Run Code Online (Sandbox Code Playgroud)
伪随机生成器,例如rand(),只是一个数学函数,它接受输入 - 种子 - 并对其进行一些处理.它返回它产生的新值,并将其设置为新种子.下次它将使用新的种子值.
因为计算机是确定性的,所以每次rand()使用相同的种子调用时,它都会产生相同的输出值.这就是为什么它是伪随机的.
在您的示例中,您使用了相同的种子两次,因为time(0)以秒为单位返回时间,并且您的两个函数调用在同一秒内发生(因为计算机非常快).
正如其他评论者所说,只需要一次相当随机的值(即当前时间).
| 归档时间: |
|
| 查看次数: |
1661 次 |
| 最近记录: |