Advertisement

random numbers...

Started by January 05, 2003 04:45 PM
5 comments, last by Drakex 21 years, 10 months ago
is there any way to get random numbers in a user-definable range? the old RAND function will only return numbers between 0 and 0x7fff. i don''t want it to do that. i want to return numbers between 0 and some number the use types in. is there another random function i could use? or is there some way of mangling RAND()''s output to return a number in a certain range? thanks
_______________________________________________________________________Hoo-rah.
The easiest, (yet somewhat innacurate to get even spread) way is

randnum=rand()%(highestnum-1)+lowestnum;

ie

randnum=rand()%9;

would output a num between 0 and 8.

[Piebert Entertainment] [Ask The All-Knowing Oracle A Question]------------------------------------------------------------GDSFUBY GameDev Society For UnBanning YodaTheCodaIf you want to see yoda unbanned then put this in your sig ------------------------------------------------------------DAIAGA Dave Astle is a God Association. To join, put this in your sig!Founder and High Priest of DAIAGA[edited by - YodaTheCoda on December 10, 2003 1:57:54 PM]
Advertisement
thanks
_______________________________________________________________________Hoo-rah.
You really shouldn''t use modulus (%) with rand in that way.
I can''t be bothered to go into the details on why, but there''s several other threads here on gamedev where it''s been discussed. Search for one of them.

-Neophyte
Well, ktuluorion''s method doesn''t work from what I can see . If you want to have a number between 3 and 8, for example, with his method you would get numbers between 3 and 10. If you want to do it modulo-style, it''d look like this:

randnum=rand()%(1+Highest-Lowest)+Lowest;

Still it''s not the best way to do things but I can''t find the thread where it was discussed right now as search is still disabled . Someone posted this in it, however, when I tried it out, it didn''t work iirc...

int rand_good (int N) { return( N * rand () / ((int)RAND_MAX + 1)); }

(It actually should work.. you''d just have to combine it with the above: rand_good(1+Highest-Lowest)+Lowest
double rand_01() { return (double)rand() / (double)RAND_MAX; )

long rand_n( long n ) { return (long)( n*rand_01() ); }

long rand_nm( long nmin, long nmax ) { return rand_n( nmax - nmin ) + nmin; }

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
ahhh more
_______________________________________________________________________Hoo-rah.

This topic is closed to new replies.

Advertisement