How to generate different random numbers in a loop

2018-12-31 23:17发布

问题:

Is it possible to generate different random number, every time loop runs. For example, i have:

for (int t=0;t<10;t++)
{
    int random_x;
    srand ( time(NULL) );
    random_x = rand() % 100;
    cout<<\"\\nRandom X = \"<<random_x;
} 

But the problem is, it generates same random number everytime. Is it possible to generate different random numbers everytime loop runs?

IS there any possibility to reset random number initiallization as well?

回答1:

Don\'t use srand inside the loop, use it only once, e.g. at the start of main(). And srand() is exactly how you reset this.



回答2:

You are getting the same random number each time, because you are setting a seed inside the loop. Even though you\'re using time(), it only changes once per second, so if your loop completes in a second (which it likely will), you\'ll get the same seed value each time, and the same initial random number.

Move the srand() call outside the loop (and call it only once, at the start of your app) and you should get random \"random\" numbers.



回答3:

Do not use rand(); use new C++11 facilities (e.g. std::mt19937, std::uniform_int_distribution, etc.) instead.

You can use code like this (live here on Ideone):

#include <iostream>
#include <random>
using namespace std;

int main()
{
    // Random seed
    random_device rd;

    // Initialize Mersenne Twister pseudo-random number generator
    mt19937 gen(rd());

    // Generate pseudo-random numbers
    // uniformly distributed in range (1, 100)
    uniform_int_distribution<> dis(1, 100);

    // Generate ten pseudo-random numbers
    for (int i = 0; i < 10; i++)
    {
        int randomX = dis(gen);
        cout << \"\\nRandom X = \" << randomX;
    }
}

P.S.

Consider watching this video from Going Native 2013 conference for more details about rand()-related problems:

rand() Considered Harmful



回答4:

Try moving the seed srand outside the loop like so:

srand ( time(NULL) );
for (int t=0;t<10;t++)
{
    int random_x;
    random_x = rand() % 100;
    cout<< \"\\nRandom X = \"<<random_x;
} 

As Mark Ransom says in the comment, moving the seed outside the loop will only help if the loop is not residing in a function you are calling several times.



回答5:

I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:

    srand (time(NULL));
    (int t=0;t<10;t++)
    {
    cout << rand() % 100 << endl;
    } 


回答6:

Stop seeding the generator every time. Pull the srand call out of the loop



回答7:

Move the srand call to the start of the program. As you have it now, the time might be the same between two consecutive calls, so the random number generator will start again at the same spot.



回答8:

You need to extract the initilization of time() out of the for loop.

Here is an example that will output in the windows console expected (ahah) random number.

#include <iostream>
#include <windows.h>
#include \"time.h\"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 100;
        std::cout << \"\\nRandom X = \" << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}


回答9:

The time function probably returns the same value during each iteration of the loop.

Try initializing the random seed before the loop.



回答10:

Every iteration you are resetting the sequence of pseudorandom numbers because you are calling srand with the same seed (since the call to time is so frequent). Either use a different seed, or call srand once before you enter the loop.



回答11:

If you have randoms early on in the program you could multiply the loop variable by the time - to give a better distribution. For example

for (int t = 0; t < 10; t++){
        srand(time(NULL)*t);
        random =  rand() % GetScreenWidth();

}


回答12:

/*this code is written in Turbo C++
 For Visual Studio, code is in comment*/

int a[10],ct=0,x=10,y=10;    //x,y can be any value, but within the range of 
                             //array declared
randomize();                 //there is no need to use this Visual Studio
for(int i=0;i<10;i++)
{   a[i]=random(10);         //use a[i]=rand()%10 for Visual Studio
}
cout<<\"\\n\\n\";
do
{   ct=0;
    for(i=0;i<x;i++)
    {   for(int j=0;j<y;j++)
        {   if(a[i]==a[j]&&i!=j)
            {   a[j]=random(10);    //use a[i]=rand()%10 for Visual Studio
            }
            else
            {   ct++;
            }
        }
    }
}while(!(ct==(x*y)));

Well I\'m not a pro in C++, but learnt it in school. I am using this algo for past 1 year to store different random values in a 1D array, but this will also work in 2D array after some changes. Any suggestions about the code are welcome.



回答13:

Don\'t know men. I found the best way for me after testing different ways like 10 minutes. ( Change the numbers in code to get big or small random number.)

    int x;
srand ( time(NULL) );
x = rand() % 1000 * rand() % 10000 ;
cout<<x;


标签: c++ loops random