gcc newbie: rand()

Rick Dearman rick@ricken.demon.co.uk
Sun Dec 12 15:29:00 GMT 1999


I think this is what you want:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int
get_rand(int range)
{
  int mrand;
  mrand = (int)((double)rand() / ((double)RAND_MAX +1) * range);
  return mrand;
}

int
main(void)
{
  float x;
  int n;

  srand((unsigned int)time((time_t *)NULL));

  x =  get_rand(5);
  n = 1 + (6*x);
  printf("x = %d\n", n);

  return 0;

}


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!
> */


More information about the Gcc-help mailing list