mercredi 12 juillet 2017

rand() with srand() is giving strangely similar results. The return from rand() is very similar

This is a seemingly common question, so I hope I don't sound redundant. But the range returned from rand() should be between 0 and RAND_MAX, however when I do a very simple rand statement, I'm always getting returns within a very small range.

This range is something like 1,4XX,XXX,XXX. I figured this might be a clock thing, so I waited thirty minutes and I'm still getting numbers in the same range.

Here is some sample output from twenty minutes ago:  Rand() Return: 1439810968, Rand() Return: 1439827775, Rand() Return: 1439827775, Rand() Return: 1439844582, Rand() Return: 1439878196

and here is sample output from just now:

 1456483512, 1456500319, 1456500319, 1456517126, 1456533933

I know rand() isn't perfect, but this seems too similar to be correct. If the range is 0 - RAND_MAX, it seems weird that every number returned is in the same range.

Here is the code I was testing:

#include <iostream>
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main(int argc, char const *argv[])
{
    /* declarations */
    srand(time(NULL));

    std::cout << std::rand() << std::endl;
    std::cout << std::rand()%100 << std::endl;
    return 0;
}

I don't think I needed all those #include statements, but I saw other people using them so I included them just incase it would affect my output, but it didn't.




Aucun commentaire:

Enregistrer un commentaire