Why does rand () return the same value with srand (time (null)) in this for loop?

I have the following code

#include<iostream>
#include "time.h"

using namespace std;

void printRandomNumber()
{
    srand(time(NULL));
    cout << rand() % 3;
}

int main()
{
    for(int i=0; i<=5; i++)
    {
        printRandomNumber();
    }
system("pause");
}

The conclusion is the same number as six times, I would like to print a combination of numbers.

+3
source share
5 answers

Because you sow the same value every time - it timeonly has second-level accuracy, and I'm sure that your computer will be able to process these six iterations of the cycle in one second .; -]

Seed once, at the beginning of the program.

+17
source

Because, of course, you usually feed the srand with the same seed every time, because your cycle will take much less than 1 second.

The srand function should be called only once in the life of your program.

+3
source

srand , . , . , . , .

+3

, . 2 :

  • srand(time(0)) . .

  • If you still want to have srand(time(0))main () outside, you can replace srand(time(0))with srand(rand())in your function. This will create a random random seed, which will lead to an improvement in the situation.

+1
source

This is what will work for your case.

    #include<iostream>
    #include "time.h"

    using namespace std;

    // Reset the random number generator with the system clock.
    void seed()
   {
       srand(time(0));
   }

    void printRandomNumber()
    {        
        cout << rand() % 3;
    }

    int main()
    {
        seed();
        for(int i=0; i<=5; i++)
        {
            printRandomNumber();
        }
    system("pause");
    }
0
source

All Articles