【发布时间】:2019-05-28 11:12:29
【问题描述】:
我想知道为什么在程序开始时播种 srand 而不是在我使用它的地方是有利的。
我在程序开始时播种 srand 时生成伪随机数,但是当我在调用生成数字的函数中播种 srand 时,我得到的数字都是一样的
#include <iostream>
#include <ctime>
using namespace std;
int rng()
{
const int SIZE = 10;
int rng[10];
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
rng[i] = rand() % 128 + 1;
return rng[i];
}
}
int main()
{
int array;
//srand(time(NULL)); If i put it here i get actual random numbers
cout << "Welcome to the program";
cout << "\nthis is your rng\n";
for (int i = 0; i < 10; i++)
{
array = rng();
cout << array << endl;
}
return 0;
}
当我运行程序时,所有数字都是相同的,但是当我从 rng 函数中删除种子并取消注释主模块中的 srand 时,数字是伪随机的,这正是我想要的。我想知道为什么。我调查过它,听说我用时间播种 srand ,当我运行该函数时,循环迭代得如此之快,以至于所有的数字都是用相同的种子值生成的,所以它们都是一样的,但我想知道这和在 main 中有什么区别 srand(time(NULL)) 因为无论哪种方式,函数生成数字的速度都不会那么快,它们无论如何都会处于相同的种子值?由于输出不同,它看起来不是那样,但我很好奇,为什么?
【问题讨论】: