[gameprogrammer] Re: Random Integer Problem :(

      In  Numerical Recipes in C: The Art of Scientific Computing (William H.
      Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
      York:  Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
      ing comments are made:

             "If you want to generate a random integer between 1 and 10,  you
             should always do it by using high-order bits, as in

                    j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

             and never by anything resembling

                    j = 1 + (rand() % 10);


from unix man page of rand $> man 3 rand

On 9/24/06, Chris Nystrom <cnystrom@xxxxxxxxx> wrote:


On 9/23/06, Sahan Chandrasekara <sahanthegamecreator@xxxxxxxxx> wrote:
> Hi,
>
> I'm trying to use this code to generate a random number between 1 and six
inclusive:
>
>
> int random_int() {
>     srand(time(NULL));
>     int random_num=rand()%7;
>     return random_num;
> }
>
> But it dosen't work. My program is programmed to quit immediantly if the
number is not between 1 and six inclusive, and that is what it does

I believe for 1-6 you want something like:

random_num = ((rand() % 6) + 1);

Chris

--
E-Mail: Chris Nystrom <cnystrom@xxxxxxxxx >
http://www.newio.org/
AIM: nystromchris


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: