Hello,
I'm having some problem with the floor and rand functions.
What I want to do is create a random number 1-6 and make sure it's a hole number.
Right now I'm using:
1 2
d1 = rand()%6 +1;
d1 = floor(d1);
But it gives me a warning for changing 'int' from 'double'
Anyone know why and/or a better way?
If you could explain to me in dpeth that would be best.
floor() is a function designed to truncate (well, it's not quite truncation, but it's close enough) a floating point number d1 is apparently an int, so it makes no sense to call floor() on it. Plus, rand() will never return a fractional. Plus, % automatically truncates fractional operands.
Ok, then. Also I found this code for a 'better' random number:
1 2 3 4 5 6 7 8 9
int randomNumber(int hi) //the correct random number generator for 0-hi
{
int value=((float)rand()/RAND_MAX)*(hi+1);
if(value>hi)
{
value = 0;
}
return value;
}
What does this do, how is it better and how do I use it?
1) It generates random numbers, per the comment
2) The only way that it is better is that it generates a uniform distribution for all inputs hi, whereas
rand() % hi does not (for all inputs).
3) Call it; the comment says what it does.
#include <ctime>
srand((unsigned)time(0))// sets the rand seed to the clock so its random every time
int rand_NUM = (rand()%6)+1; // creates random number 1 - 6
It does what it says it does. The first line initializes the random number generator using (hopefully) a different starting seed. The second line generates a random number in the range [ 1, 6 ].
However there is a very slight bias in the numbers it generates due to the fact that MAX_INT is not evenly divisible by 6. Though for any application where rand() is sufficient the bias will not be a problem.
srand() seeds the random number generator with the given value.
rand() implements an LCRNG (linear congruential random number generator). An LCRNG is one which has the formula:
RN(i) = ( c1 * RN(i-1) + c2 ) mod p
where c1 and c2 are carefully chosen constants (you have no control over them). p is 2^32 for 32-bit machines. RN(k) is the kth random number. RN(0) is the seed. srand() sets RN(0).
rand() then simply runs the above formula once, generating RN(i).