In article <pa****************************@spammer.die>,
Mark Healey <di*@spammer.die> wrote:
Here's the code:
signed char xMove, yMove, subx, suby;
[a bunch of stuff snipped]
xMove=(3*((float)rand()/(float)RAND_MAX))-1;
yMove=(3*((float)rand()/(float)RAND_MAX))-1;
I run srand() in main. When I run it without the -1 I get 0-2 as expected
but when I run it with them I get 0 and 1.
Why?
rand() will rarely come out as RAND_MAX, so the division is almost
always going to come out as something less than 1. When you multiply
it by 3, you are almost always going to come out with something less than 3.
Subtract 1 and you are almost always dealing with something less than 2.
You then convert that to an integer value by truncation instead of
rounding, so the maximum value will almost always be 1.
About 1/3 of the time, the float division of rand() by RAND_MAX will
come out less than 1/3; multiplied by 3 that would come out less than 1;
subtract 1 and the result will be less than 0. You then convert that
to a signed integer value. Check your results again: you are
probably generating some -1's.
Note by the way that the constants 3 and 1 in your expression
are operating on float values, so you might as well use float constants,
e.g. 3.0f and 1.0f .
--
Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us. -- Ecclesiastes