Archived

This topic is now archived and is closed to further replies.

Exellon

%

Recommended Posts

Modulos. Say, if I have a the number 3 and I put 3%2, the output would be one. Think of it this way, it's basically, 3/2, BUT instead of using the normal answer, the answer is the difference. For example, if there was 5%4, the answer would be one.

Say, for example, if there was an asteroids game, and the y axis was 4, and the guy suddenly went to 5 on the y axis, using a modulo, he'd appear at one instead of going off the screen.

5%4=1 See?

[edited by - Andrew Nguyen on August 12, 2002 12:11:54 AM]

Share this post


Link to post
Share on other sites
Assuming you mean the % operator in C++. It is the modulus operator ( or in english the remainder operator ). It will return the remainder. So for example:


  

int six = 6;
int four = 4;

int remain = six % four;

// remain is now 2 since 6/4 = 1 Remainder 2




--------
Andrew

Share this post


Link to post
Share on other sites
Exellon:

(rand()%360) would give you a random integer between 0 and 359. Here's a quick table to help you understand:

n | n % 6
-------------
0 | 0 <- 0/6 = 0, with a remainder of 0
1 | 1 1/6 = 0, with a remainder of 1
2 | 2 2/6 = 0, " " " " 2
3 | 3 .
4 | 4 .
5 | 5 .
6 | 0 <- 6/6 = 1, with a remainder of 0
7 | 1

The important thing to remember is that this is integer division, not floating point.

John.

[edited by - JohnAD on August 13, 2002 1:09:17 AM]

[edited by - JohnAD on August 13, 2002 1:09:48 AM]

Share this post


Link to post
Share on other sites
Especially when you''re mod-ing by a power of two (%256, for instance), you''re simply masking out the higher bits and using the lower ones, which are less random. It''s not quite as bad for mod-ing by other numbers, but still not a good idea. The correct way would be: (rand () * 360) / RAND_MAX

Share this post


Link to post
Share on other sites
Modulos are neat, but they are slow. In cases where the modulo is a power of two - like 256, a bit mask can be used instead
x & 0xFF - 0xFF is 255 ~~ x % 256
This works because of the properties of binary numbers - but Kippesoep''s division approach is probably better given the power of today''s cpus.

Share this post


Link to post
Share on other sites