【问题标题】:Trying to generate random array of integers, getting the same list each run. C++ [duplicate]尝试生成随机整数数组,每次运行都获得相同的列表。 C++ [重复]
【发布时间】:2016-09-05 21:44:00
【问题描述】:

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

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

【问题讨论】:

    标签: c++ random negative-number


    【解决方案1】:

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

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

    【讨论】:

    • 对随机数使用srand 多年来一直不是基于标准的最佳解决方案。
    【解决方案2】:

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

    【讨论】:

    • 使用srand 随机数多年来一直不是基于标准的最佳解决方案。
    • 好的,这对我来说是个新闻——什么是更好的解决方案?
    • 嗯,好的,对于 C++11 - 感谢您的提醒 ;)
    猜你喜欢
    • 2015-11-10
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多