I got this c++ macro and wonder what they mean by code%2 (the percentage sign) ?
#define SHUFFLE_STATEMENT_2(code, A, B)
switch (code%2)
{
case 0 : A; B; break;
case 1 : B; A; break;
}
I got this c++ macro and wonder what they mean by code%2 (the percentage sign) ?
#define SHUFFLE_STATEMENT_2(code, A, B)
switch (code%2)
{
case 0 : A; B; break;
case 1 : B; A; break;
}
It means the remainder of a division. In your case, divide by 2 and the remainder will be either 0 or 1.
It means modulo. Usually (x % 2)
discriminates odd and even numbers.
It is for taking a modulus.
Basically, it is an integer representation of the remainder.
So, if you divide by 2 you will have either 0 or 1 as a remainder.
This is a nice way to loop through numbers and if you want the even rows to be one color and the odd rows to be another, modulus 2 works well for an arbitrary number of rows.
Thats the modulo. It returns whats left after division:
10/3 will give 3. - 1 is left.
10%3 gives this 1.
Modulo returns the remainder that is left after division. It is helpful when you're tasked with determining even / odd / prime numbers as an example:
Here's an example of using it to find prime numbers:
int main(void)
{ int isPrime=1; int n;
cout << "Enter n: ";
cin >> n;
for (int i=1; i<=n; i++)
{
for (int j=2; j <= sqrt(static_cast<double>(i)); j++)
{
if(!(i%j))
{
isPrime=0;
break;
}
}
if (isPrime)
cout << i << " is prime" << endl;
isPrime=1;
}
return 0;
}
In case somebody happens to care: % really returns the remainder, NOT the modulus. As long as the numbers are positive, there's no difference.
For negative numbers there can be a difference though. For example, -3/2 can give two possible answers: -1 with a remainder of -1, or -2 with a remainder of 1. At least it's normally used in modular arithmetic, the modulus is always positive, so the first result does not correspond to a modulus. C and C++ allow either answer though, as long as / and % produce answers that work together so you can reproduce the input (i.e. -1x2+-1->-3, -2x2+1=-3).