0

我正在尝试生成两个随机数数组。一个数组用于高度,另一个用于文本艺术鱼缸的宽度。但是数组总是有相同的重复数字。

例如:[ 2, 2, 2, 2 ] 或 [ 9, 9, 9]

我一定是错误地设置了循环,但我需要帮助看看出了什么问题。

    //Generate random numbers for fish positions in vector
    if ( fish_collection.size() != 0 )
    {
        int randHeight[fish_collection.size()];
        int randWidth[fish_collection.size()];

        for ( int i = 0; i < fish_collection.size(); i++ )
        {
            srand (time(NULL));
            randHeight[i] = rand() % 10 + 1;
            randWidth[i] = rand() % (tank_size - 5) + 1;
        }

        //random number printed test
        for ( int i = 0; i < fish_collection.size(); i++ )
        {
            cout << randWidth[i] << ',';
        }
        cout << endl;

        //Enter the fish in random position
        for ( int j = 0; j < fish_collection.size(); j++ )
        {
            tank_frame[randHeight[j]].replace ( randWidth[j], fish_collection[j].size(), fish_collection[j] );
        }
    }
4

2 回答 2

2

您只需在程序中调用srand(time(NULL))一次(通常在 main 的开头)。

我相信不止一次调用它会重置整个序列,这解释了为什么你每次都得到相同的数字(第一个)。(而且你总是得到相同的第一个的原因是,很可能这些电话非常接近,时间是一样的)。

'time(NULL)' returns the number of seconds since 00:00 1st January 1970, which explains why 'srand(time(NULL))' always seeds to the same value: It executes in less than one second, so time(NULL) returns the same value. (See this link)

于 2013-07-22T21:00:05.663 回答
0

You call srand() every time when you call rand() function. This is incorrect: srand() should be used only once in the beginning of your program, because the value you pass to it sets the whole sequence of further rand() values. In this example you always call srand() with the same argument (because time updates not very often), thus the rand() sequence was always the same, thus call to rand() always returned the same value.

于 2013-07-22T21:05:11.100 回答