试图生成随机的整数数组,每次运行都得到相同的列表。 C ++

时间:2016-09-05 21:44:00

标签: c++ random negative-number

为什么每次运行时都会产生相同的数组?

int arr[100];
for (int i = 0; i < 100; i++) {
    arr[i] = rand() % 11 + (-5); 
}

2 个答案:

答案 0 :(得分:2)

您需要种子随机数生成器,例如当前时间。

#include <time.h>
#include <stdlib.h>
srand(time(NULL));

答案 1 :(得分:1)

使用std::srand(std::time(0));设置随机种子。要获得可重现的结果,请使用相同的种子,请参阅http://en.cppreference.com/w/cpp/numeric/random/srand