From: mert0407 AT sable DOT ox DOT ac DOT uk (George Foot) Newsgroups: comp.os.msdos.djgpp Subject: Re: Help! Random is not working right Date: Tue, 08 Apr 1997 18:01:20 GMT Organization: Oxford University Lines: 25 Message-ID: <334a8739.3489902@news.easynet.co.uk> References: <3349B612 DOT 68C AT ucsu DOT Colorado DOT edu> NNTP-Posting-Host: foot.easynet.co.uk To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp On Mon, 07 Apr 1997 23:05:54 -0400, William Heymann 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