0

I have these snippets of code:

char letrarand()
{
    time_t t;
    srand(time(NULL));                                                  
    char randomletter = 'A' + (rand() % 26);
    return randomletter;
}

char criameses()
{
    int contador = 0;
    for (contador = 0; contador < 31;++ contador) 
        {
            *(pjaneiro + contador) = letrarand();
        }

Where pjaneiro is a pointer to a 31 element array. Theoretically this works and would assign a random letter to each element of the array, but as it turns out it always assigns the same letter.

My best guess as to why this happens is that the time() functions is only accurate to a second so the seed to the random number generator is always the same because my computer executes the code in less than one second. Is there a way for me to better seed the random number generator?

Henrique
  • 45
  • 4
  • 3
    Just seed once. Not each time you need a random number. – Michael Burr Jan 02 '17 at 19:57
  • 3
    [srand() — why call it only once?](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – BLUEPIXY Jan 02 '17 at 20:01
  • "is that the time() functions is only accurate to a second so the seed to the random number generator is always the same" --> not quite. Commonly `time()` returns an integer count of seconds, but others exist that return a `double` to fractions of a second. `srand(unsigned int seed);` would convert the higher precision time result to a reduced accuracy (to the second) when passed to `unsigned seed`. IAC, this is not the primary issue, calling `srand()` once (like in `main()`) will solve your initial concerns. – chux - Reinstate Monica Jan 02 '17 at 20:28

0 Answers0