0
Why am I having trouble with random numbers?
When I try to generate a radnom number with rand() it always ends up in the same result, is there a fix to this? I'm using c++.
4 odpowiedzi
+ 5
William Osman in most cases you have to "seed" the random number generator with a value. this is done to prevent rand() from giving same pseudo random numbers. In C/++ you can use
srand(int seed);
change seed value every time you run, so a solution is using srand with the clock or time.
still the values that rand returns are not truly random, but they won't be the same in each run.
ex:
clock_t t= clock();
srand(t);
int rnd = rand();
or:
srand(clock());
int rnd = rand();
You only need to run srand once, no need to seed random generator before every call to rand. getting "truely random" numbers isn't easy and in most cases you don't need it. seeding with clock() or time() is enough unless you want to do some cryptography tasks, in that case on linux you can read random numbers from character device /dev/random.
another "pseudo random" number generator device is /dev/urandom.
+ 8
William Osman ,
to get useful help we need to see your code. please link it here.
also give a task description what are you going to do with the random number/s
+ 1
Thanks for the help!
0
William Osman maybe this code will help you
seed (time ( null ))
and so on
https://code.sololearn.com/cOZbVYm53O9K/?ref=app
https://code.sololearn.com/cZOpV1zkC4cm/?ref=app