Originally posted by: DaveSimmons
look up the ANSI C functions rand() and srand() to "seed" the random number generator. the % mod operator can trim the value to any range you want, e.g.
pick = 1 + (rand() % 10) ; // 1 - 10
pick = rand() % 50 ; // 0-49
people often use the clock to seed the RNG, for example:
srand( (unsigned)time( NULL ) ) ;
you only need to do this once, at the start of your program or before the first call to rand() .
Good idea for short-lived processes!Originally posted by: BingBongWongFooey
I like to use a combination of time(NULL) and getpid(), so that multiple executions within the same second don't result in identical "random" numbers.
Agreed if you need highly random numbers, but this looked like an Intro to C++ programming assigment so I wanted to keep it simple.Originally posted by: Armitage
This is generally considered to be bad practice, as it only uses the low order bits of the random number, which may not be very random for some of the crappier algorithms.
You should use something like:
pick = 50*rand()/RAND_MAX;
(got burned by this once)
the RAND_MAX Armitage mentioned is a constant equal to the largest value that rand() can possibly return. So if you do the math,Originally posted by: LeetViet
So
card = 50*rand()/3; ?
Originally posted by: DaveSimmons
the RAND_MAX Armitage mentioned is a constant equal to the largest value that rand() can possibly return. So if you do the math,Originally posted by: LeetViet
So
card = 50*rand()/3; ?
int y = (x * rand() ) / RAND_MAX
will set y to a value between 0 and x. Either that or garbage after an integer overflow
edit: actually between 0 and x not the (x-1) I said originally:
"The constant RAND_MAX is the maximum value that can be returned by the rand function. RAND_MAX is defined as the value 0x7fff."
If this were an environment where you cared about the best possible randomness, you could use the above approach but cast the intermediate values to 64-bit long long ints to prevent overflow.
Originally posted by: LeetViet
How can I randomize between X numbers of specific numbers?
Originally posted by: Armitage
Originally posted by: LeetViet
How can I randomize between X numbers of specific numbers?
Well, the discussion above gives you random numbers between 0 and some other number. Getting random numbers between 2 nonzero numbers is left as an exercise for the student.
Originally posted by: LeetViet
Originally posted by: Armitage
Originally posted by: LeetViet
How can I randomize between X numbers of specific numbers?
Well, the discussion above gives you random numbers between 0 and some other number. Getting random numbers between 2 nonzero numbers is left as an exercise for the student.
This isn't for a school project.
What do you mean by 2 nonzero numbers?
Originally posted by: Ameesh
you should get in the habit of... rand whenever you can