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++.

12th Feb 2023, 9:46 AM
William Osman
William Osman - avatar
4 Respuestas
+ 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.
12th Feb 2023, 10:15 AM
Tina
Tina - avatar
+ 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
12th Feb 2023, 11:40 AM
Lothar
Lothar - avatar
+ 1
Thanks for the help!
12th Feb 2023, 12:21 PM
William Osman
William Osman - avatar
12th Feb 2023, 1:23 PM
BroFar
BroFar - avatar