0
int RandomNum(int n, int nMax)
{
    srand(time(NULL));
    int r = 1 + rand() % nMax;
    while (r == n)
    {
        r = 1 + rand() % nMax;
    }
    return r;
}

int _tmain(int argc, _TCHAR* argv[])
{

    for (int i = 0; i < 10; i++)
    {
        int x=RandomNum(4, 100);
        std::cout << x << "\n";
    }

    return 0;
}

Is my VS13 going wild or what because it is always outputting the same number in every execution of the code above ? Debugging shows the output display different numbers but one time run does not :(

razlebe
  • 7,134
  • 6
  • 42
  • 57
user3431664
  • 51
  • 1
  • 10
  • 1
    You need to move `srand()` to `main()`, before the loop. – pmg May 05 '14 at 14:29
  • could you please explain more ? – user3431664 May 05 '14 at 14:29
  • See [my answer to a question posted a year ago](http://stackoverflow.com/a/15571186/25324). – pmg May 05 '14 at 14:31
  • possible duplicate of [Problems when calling srand(time(NULL)) inside rollDice function](http://stackoverflow.com/questions/15570803/problems-when-calling-srandtimenull-inside-rolldice-function) – lethal-guitar May 05 '14 at 14:33
  • You seed `rand()` by calling `srand(time(NULL))`. The resolution of time is low enough that `time(NULL)` does not change at all during the loop so you keep resetting your random generator to the same state. When you out put numbers to console you see them change because outputting to console is a slow operation and adds delays to your loop. – kkuryllo May 05 '14 at 14:35

2 Answers2

3

The loop is short, and will loop over all values within a single second. That causes all your calls to rand to start with the same seed.

Only call srand once, preferably very early in the main function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You‘re specyfing the seed every time. Instead you have to do it only once.

Move srand(time(NULL)) to the beginning of main.

Banex
  • 2,890
  • 3
  • 28
  • 38