+ 4

% Modulo

When would you use this operator??? It just seems random.

13th Apr 2018, 12:39 PM
Bethany
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
14th Apr 2018, 1:24 PM
Freddy
+ 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
13th Apr 2018, 12:49 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 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
13th Apr 2018, 2:09 PM
cyk
cyk - avatar
+ 3
that modulo hard to understand , especially in the java/python/cpp !
14th Apr 2018, 4:56 AM
Azize Ez-hraoui
Azize Ez-hraoui - avatar
+ 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++ }
13th Apr 2018, 5:00 PM
Freddy