Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ random number generator

Tags:

c++

random

srand

I am writing an lottory application. I have a function called generateLotteryNumbers this takes in an array and fills that array with 5 random numbers. What I want to do is have this function produce a different set of random numbers every time this function is called.

void generateLotteryNumbers(int lotteryNumbers[])
{

    srand (time(NULL));
    const int arraySize = 5;
    int index = 0;

    while (index < arraySize)
    {
        lotteryNumbers[index] = rand() % 50 + 1;
        cout << lotteryNumbers[index] << endl;
        index++;
    }
}

The output at the moment is eg:

5
24
45
26
47

Repeated twice.

like image 867
KingJohnno Avatar asked Dec 25 '22 18:12

KingJohnno


1 Answers

Call srand exactly once, usually early in the code in main.

like image 188
Pete Becker Avatar answered Jan 08 '23 23:01

Pete Becker