c++ - 为什么这个程序输出相同的结果 4 次?

标签 c++ random random-seed

<分区>

我希望这个程序生成 4 个不同系列的 4 个随机数。该程序当前为每个系列输出相同的数字。知道发生了什么事吗?我认为它与种子有关,但我不知 Prop 体是什么。

#include <iostream>
#include <cstdlib>
#include <ctime> 

using namespace std;
int main()
{
    int lotArr[6];
    int j = 0;
    int k = 0;
    int m = 0;
    int n = 0;
    int i = 0;
    bool crit = false;

    //interates through 4 sequences
    for(int i = 0; i < 4; i++ )
    {
        srand(time(NULL));
        //generates each number in current sequence
        for(m = 0; m < 4; m++)
        {
            lotArr[m] = rand() % 30 + 1;
        }

        //output
        for(n = 0; n < 4; n++)
        {
            cout << lotArr[n] << " ";
        }
        cout << endl;
    }
    return 0;
}

最佳答案

这是因为 time(NULL) 以秒为单位返回 UNIX 时间戳。现在,您的每个外部 for 循环都在不到一秒的时间内执行。因此, srand(time(NULL)) 基本上将每个循环的种子设置为相同。我建议拿 srand(time(NULL));走出循环,你会没事的。像这样:

#include <iostream>
#include <cstdlib>
#include <ctime> 

using namespace std;
int main()
{
    int lotArr[6];
    int j = 0;
    int k = 0;
    int m = 0;
    int n = 0;
    int i = 0;
    bool crit = false;

    srand(time(NULL));

    //interates through 4 sequences
    for(int i = 0; i < 4; i++ )
    {
        //generates each number in current sequence
        for(m = 0; m < 4; m++)
        {
            lotArr[m] = rand() % 30 + 1;
        }

        //output
        for(n = 0; n < 4; n++)
        {
            cout << lotArr[n] << " ";
        }
        cout << endl;
    }
    return 0;
}

关于c++ - 为什么这个程序输出相同的结果 4 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998496/

相关文章:

c++ - ShellExecuteEx 工作不稳定

c++ - 如何简洁、便携、彻底地播种mt19937 PRNG?

python - 这段代码 Python 3.3 有什么问题

c - 如何在掷骰子时成功地在 C 语言中使用 rand,而无需花费 1000 秒的时间才能获得正确的结果?

Python random.seed 表现异常

r - 我的Windows 10特有R再现性问题

c++ - 在编译时获取未初始化的内存警告

c++ - 是否有一种内存有效的方法来探索从输入排列生成的解决方案?

c++ - 使用 C++ 对象 Q_PROPERTY 绑定(bind)复选框 'checked' 属性

c# - 将多维数组的 n 个随机元素设置为一个值