I\'m trying to generate random number between 0 and 40(inclusive). So the code I Implemented is this-
y=rand()%41;
However everytime I click c
It is generated by an argument passed seed. To generate different numbers add this before calling the rand()
function:
srand (time(NULL));
This generates a new random seed.
You should have this library: #include <time.h>
And if you still have an error use this one as well: #include <stdlib.h>
As for how it works, it depends. Many implementations use a Linear Congruential Generator, with different parameters.
rand()
generates only pseudorandom numbers. This means that every time you run your code you will get exactly the same sequence of numbers.
Consider using
srand(time(NULL))
to get every time different numbers. In fact a possible implementation for rand
is
next = next * 1103515245 + 12345;
return (UINT32)(next>>16) & RAND_MAX;
where next
is defined as
static UINT32 next = 1;
Calling srand()
has the effect of changing the initial value of next
, thus changing the "next" value you get as result.
Reason is that rand() is using the same seeding everytime you run. You have to seed it yourself. srand ( time(NULL) );` is usually used to initialize random seed.
The algorithm used for rand
is unspecified by the C Standard,
By specification, if you don't call srand
before a call to rand
in your program, it is as if srand(1)
was called: the seed value will be 1
at every execution of the program and the generated sequence will be always the same.
A common way to have different seeds for different executions of the program is to use a seed which depends on the current time like:
srand(time(NULL));
This is actually a FAQ on comp.lang.c. Here's the solution that they suggest:
(int)((double)rand() / ((double) RAND_MAX + 1) * N )
Where N
is the ceiling of your range of random numbers. This is because the low order bits on bad C compilers are "shockingly non-random". This doesn't get around the need for using srand(). Note, however that srand( time(NULL) ) should be called outside of your loop... time() has a resolution of 1 second, so calling it inside of the loop will re-initialize your random number generator to the same seed many times in a row.
The need for this is probably largely historical, I'm sure that modern compilers probably don't have random number generators which emit really bad random numbers, but I remember writing a program using the Borland C compiler which would cycle through about 5 numbers when I used rand() % 41
repeatedly.