简体   繁体   中英

How to generate different random numbers in a loop in C++?

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?

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

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.

Do not use rand() ; use new C++11 facilities (eg 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;
    }
}

PS

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

rand() Considered Harmful

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.

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

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();

}
/*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.

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

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.

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

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

Try initializing the random seed before the loop.

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.

The way the function rand() works is that every time you call it, it generates a random number. In your code, you've called it once and stored it into the variable random_x . To get your desired random numbers instead of storing it into a variable, just call the function like this:

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM