gcc newbie: rand()

Jan Dvorak johnydog@go.cz
Fri Dec 10 04:40:00 GMT 1999


On Fri, 10 Dec 1999, Joachim Bauernberger wrote:

> /*  hi there!
> *
> *  can anybody tell my why the following code compiled with:............
> 
> *  gcc -g -D_GNU_SOURCE filename.c -o outputfile
> *
> *  ....generates all sort of strange numbers but when compiled under
> borland gives me the desired *   random numbers between 1 and 6  ??? how
> do i do it to get the numbers between 1 and 6.
> *  this example is from a book about C so it can't be that wrong, can
> it?
> */
> 
> #include <stdlib.h>
> #include <stdio.h>
> 
> #define SEED 12345
> 
> main()
> 
> {
> 
>     float x;
>     int n;
> 
>         srand(SEED);
> 
>             x = rand() /32768.0;
>             n = 1 + (int) (6 * x);
> 
>       printf("x = %d", n);
> }
> 
> /*Thank's
>                     Joachim!
> */
> 

Yes, it's hard to believe, but even books can be wrong :) Your book
complains about Borland C compiler. This compiler has limit for generating
random numbers between 0 and 32768, so that's what was '/32768.0' for. GCC
uses number which is defined by RAND_MAX so, after correction that line
should be:

		x = rand() /RAND_MAX;

anyway, please refer to rand() man pages, because random number
generating is very complex theme.

Happy coding!
Jan Dvorak

 



More information about the Gcc-help mailing list