Mail Archives: djgpp/1997/04/09/07:10:57
On Mon, 07 Apr 1997 23:05:54 -0400, William Heymann
<heymann AT ucsu DOT Colorado DOT edu> wrote:
>I am having a major problem with my program. The random fuction does not
>seem to be working right.
>
>random() & 9 only returns 0, 1, 8, and 9. I put the funcition in a loop
>and that is the only numbers it ever returns. I then changed the 9 to a
>5 and then I got 0,1,4, and 5. I need to get all the intergers within
>that range not just the four extremes. Can anybody explain why this is
>happening.
Use (random()%9) instead of & and it will return 0,1,2,3,4,5,6,7 or 8.
If you want numbers from 0 to 9, use (random()%10).
& is bitwise and; 9 is 1001, so x&9 returns only bits 0 and 3 of x.
These can only produce 0,1,8 and 9. % returns the remainder after
division, which is what you want.
You are probably getting confused here because in place of, for
example, x%4, you can write x&3. This only works if the number (4 in
this case) is a power of two.
--
George Foot
- Raw text -