Average
Average

Reputation: 165

Why does rand() return the same value using 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 output is the same number repeated six times, I would like it to print out a mix of numbers.

Upvotes: 4

Views: 5459

Answers (5)

HyperVol
HyperVol

Reputation: 146

This is because your random seed is essentialy the same. You have 2 solutions here :

  • You can put srand(time(0)) at the beginning of your code. This will generate better random sequence for every loop.

  • If you want to have your srand(time(0)) outside of main() anyway , you can replace srand(time(0)) with srand(rand()) within your function. This will generate a random random seed , resulting in better situation.

Upvotes: 0

Ahmed Masud
Ahmed Masud

Reputation: 612

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

Upvotes: 0

ildjarn
ildjarn

Reputation: 63005

Because you're seeding with the same value each time – time only has second-level precision, and I'm quite sure your computer can process those six loop iterations within one second. ;-]

Seed once, at the beginning of the program.

Upvotes: 19

Qaz
Qaz

Reputation: 61970

You should use srand once, at the beginning. Each possible seed corresponds to a specific set of pseudorandom numbers, which are always the same when that seed is used. Since you're going based off of seconds, you're not giving it time to change. Therefore, you're getting the first number of the same set of numbers each time.

Upvotes: 3

Edward Strange
Edward Strange

Reputation: 40895

Because certainly you are usually feeding the srand the same seed every time because your loop is going to take a lot less than 1 second.

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

Upvotes: 3

Related Questions