gcc newbie: rand()

Patrick Block panicoosha@sprintmail.com
Sun Dec 12 14:41:00 GMT 1999


Joachim,

Firstly, don't assume that because it's in a book it's correct! Some books
are definitely better than others.

The best book on C (IMHO) is The C Programming Language by K&R, and on p252
of that book the ANSI C standard prototype for rand() is given...

int rand (void)
rand returns a pseudo-random integer in the range 0 to RAND_MAX, which is at
least 32767.

The book you have does not give the best way for getting a specific random
number. Your book's version only works if RAND_MAX is less than 32768, which
it isn't necessarily. I think your version will work if you replace the
magic number 32768 with RAND_MAX.

If you use modulus operator, however, you can create a more elegant formula.
This is the idiom that most C programmers use as far as I'm aware:

int result;
result = (rand () % 6) + 1;

...That should do it!

I'm also pasting an example program that demonstrates one way to get a
random number. This program compiles fine with mingw32 gcc. Here's the way I
compiled it:

    gcc -luser32 -o getrand.exe getrand.c

If you're using gcc in linux or if you're using djgpp, you can omit the
"-luser32" and it should work fine.

/***-----
|
| getrand.c
|
| Demonstrates how to generate a random
| number between 1 and a given value.
|
| NOTE: In real use, you would not want
| to call srand() before every call to
| rand(), because if you call rand()
| quickly in succession, it will keep
| returning the same results. Instead,
| move the call to srand to the beginning
| of your program and only call it once.
|
| It works in this program, but only
| because getrand() is called a single
| time.
|
|
-----***/


/*** preprocessor commands ----------------------------------***/

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


/*** global variables ---------------------------------------***/


/*** function prototypes ------------------------------------***/

int getrand (int toprange);


/*** program functions --------------------------------------***/

/*>>>_____ FUNCTION: getrand _____ */

 /***-----
 |
 | get a random # between
 | 1 and toprange
 |
 -----***/

int getrand (toprange)
{
 srand (time (NULL));
 return (rand () % toprange) + 1;
}


/*>>>_____ FUNCTION: main _____ */

 /***-----
 |
 | get toprange from
 | command line, get
 | and display a random
 | number between 1 &
 | toprange
 |
 -----***/

int main (int argc, char *argv [])
{
 int toprange = 0;

 if (argc == 2)
  toprange = atoi (argv [1]);
 if (! toprange)
 {
  printf ("\nProper usage:\n\n"
    "%s #\n"
    "Where # is positive number that "
    "represents the top value for "
    "the returned random number.",
    argv [0]);
  return 1;
 }
 printf ("\n\nRandom number between 1 & %d:\t%d",
  toprange,
  getrand (toprange));
 return 0;
}





More information about the Gcc-help mailing list