+ 4
% Modulo
When would you use this operator??? It just seems random.
6 Respostas
+ 1
Another useful use is when you need a random number with a certain max value in a language that only supports getting "a random number".
In C and C++ the rand() function simply gives back a number between 0 and MAX_INT. If you need a random number between 0 and 12 you do:
rand() % 12
+ 9
"It just seems random." seems random in this context. lol :D
To help explain it to you, in programming if you divided 10 by 3, it would return the int value of 3 to you. As we know from basic math, 10 divided by 3 is 3 with a remainder of 1. In order for us to see what is remaining, we use the modulo operator. So you use it anytime you want to see if there is a remainder or not.
10 % 3 = 1
+ 3
To add to what Fata1 Err0r said it is used mostly to see if a number can be divided by another one or not. Id there is a remainder it is not, if there is not then it is divisible... Anytime you are trying to get even numbers for instance that is the go-to operator
+ 3
that modulo hard to understand , especially in the java/python/cpp !
+ 2
Check if a number is odd or even:
if (a % 2 == 0)
// even
Or when cycling through a list:
int i = 0;
while (cycling_must_continue)
{
// something with mylist[i % mylist.size]
i++
}