为什么每次for循环的输出都完全相同

Why is the output of the for loop the exact same result each time?

本文关键字:输出 for 循环 为什么      更新时间:2023-10-16

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

#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;
}

这是因为时间(null(在几秒钟内返回unix时间戳。现在,您的每个外部循环都以少于一秒钟的速度执行。因此,srand(时间(null((本质上将种子设置为相同的每个环。我建议乘坐srand(时间(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;
}