Generate random numbers

Aug 30, 2010 at 8:07pm
hello.y am trying to make a program that can generate random numbers every time y start it,using the function rand(),and y read something about it but,but y don't quite understand,because there it said,u must synchronized it with the system time so you get random values every time(or something like that).so if someone can comment a short example or something y would be grateful.so y can figure out how it works.TY
Aug 30, 2010 at 8:36pm
you need to seed the random with the current system time, to get the current system time you use clock(), which is in the <time.h> header I think.

srand(clock());

you only need to seed the random once at the start of your program, and after that you can just use the rand() function to generate a random number. If you wanted to generate a random number between 0 and a given number, you can use the modulus operator (%), so for example to get a random number between 0 and 10

rand()%11

the number after the modulus operator should be 1 higher than the maximum number you want to be the random number to be within.
Aug 30, 2010 at 9:24pm
I think its better to use srand(time(0));, because clock() could possibly give you the same value on different runs.
Aug 30, 2010 at 10:27pm
what exactly does srand(0) do? It doesn't give the same series of random numbers each time? I've never used it
Aug 30, 2010 at 10:40pm
If you supply the same seed (like zero), you get the same series of random numbers. That can be very useful for testing.
Topic archived. No new replies allowed.