[gameprogrammer] Re: Random Integer Problem :(
- From: Chris Herborth <chrish@xxxxxxxxx>
- To: gameprogrammer@xxxxxxxxxxxxx
- Date: Sun, 24 Sep 2006 11:13:16 -0400
Sahan Chandrasekara wrote:
I'm trying to use this code to generate a random number between 1 and
six inclusive:
int random_int() {
srand(time(NULL));
Only call srand() once in your program, not every time you want a random
number. This seeds the pseudorandom number generator with 'random' data
(the time in seconds), and you only need to do that once.
int random_num=rand()%7;
return random_num;
You want this instead:
random_num = rand() % 6 + 1;
}
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
number % x will give you a number between 0 and (x - 1), that's why you
add 1 to the results before returning it.
--
Chris Herborth (chrish@xxxxxxxxx) http://www.pobox.com/~chrish/
Never send a monster to do the work of an evil scientist.
---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html
- References:
- [gameprogrammer] Random Integer Problem :(
- From: Sahan Chandrasekara
Other related posts:
- » [gameprogrammer] Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
- » [gameprogrammer] Re: Random Integer Problem :(
int random_int() {
srand(time(NULL));
int random_num=rand()%7;
return random_num;
You want this instead:
}
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
- [gameprogrammer] Random Integer Problem :(
- From: Sahan Chandrasekara