Click to See Complete Forum and Search --> : Rand. Numbers


April 7th, 1999, 09:32 AM
In vc++ 5, how would I generate a random # bewtween ... 1 - 13 ( or any #).
I got it where it will give me random #'s but cant find a way to limit it to between 2 #'s.. The docs say to use RAND_MAX but gives no clue as to how to set it... if you know any other ways....help please.
Thank you!

chafey
April 7th, 1999, 11:16 AM
Use the modulus operator (%) to confine the random number to a range. If you want 1-13, I would do the following:

int RandNumber = (rand() % 13) + 1; // rand() % 13 gives a number between 0 and 12,

Chris Hafey

Gomez Addams
April 7th, 1999, 02:05 PM
To expand a little on the previous post :

int RandomRange( int min, int max )
{
// determine range of values
int range = max - min;

// idiot check
if( range <= 0 )
return 0;

// get random value
int value = rand();

// offset value to range
return ( value % ( range + 1 ) ) + min;
}

April 7th, 1999, 02:31 PM
going off the example you all have laid out for me then would I still have to "seed" it?? ( currently it is seeded using the time function)
thank you soo much!

chafey
April 7th, 1999, 04:13 PM
If you don't seed the generator, rand() will return the same values each time you run the program. Most programs seed it once, when the program first starts up. Using the time to seed the generator is fine for most applications, as long as you don't care if someone else can reproduce the random numbers. Using this approach in a security application would not be appropriate because it would be too easy to reproduce the random numbers.

Chris Hafey

Just N Time
April 7th, 1999, 04:35 PM
Nope,its for a cheesy little game, trying to learn and the tutorials are way to confusing, I was
learning C++ ( DJGPP ) and moved on to VC++.. anyway I thought I would
just div in and learn... getting there, but the lack of info.... but
thank you, now I just need to find info on reading items from files! :)
Thank you..