|
-
October 23rd, 2000, 01:42 PM
#1
Random Number Generation
Is there a function in MFC to generate a random number that is LESS
THAN a user-defined upper limit?
When I used to program in Turbo C I had used such a function. But in
MFC, I see that there are only functions that generate random numbers
between a LOWER limit and the constant RAND_MAX (which I can't change
anyway). I cannot set the upper limit.
I am looking for a method other than comparing each generated random
number with the upper limit & discarding bigger numbers.
Thanx a lot.
-
October 23rd, 2000, 01:50 PM
#2
Re: Random Number Generation
Hi,
rand() % 6
will generate random number 0..5
Note that rand() is not useful for statistical purposes - and the modulo makes it worse (a bit). But if it just should 'look random', or it is for a game or something, it#s fine.
Peter
-
October 23rd, 2000, 01:51 PM
#3
Re: Random Number Generation
// No such luck.
// Try this trick.
LONG SomeClass::Random(LONG nMin, LONG nMax)
{
// use modulus to return range then add nMin to move to offset.
return rand() % (nMax-nMin+1) + nMin;
}
-
October 23rd, 2000, 01:55 PM
#4
Re: Random Number Generation
srand((unsigned)time(NULL));
// Generate random number within the range : 0 to iMax
int iMax = 250;
int newRan = rand() % (unsigned)(iMax+1);
-
October 23rd, 2000, 04:23 PM
#5
Thanks guys
Thanks a lot for the help guys.
Really appreciate it.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|