What it is correct answer when calculating the modulus of
two numbers when one of the numbers is negative? When it comes to computers,
the answer is: it depends.
The starting point is basic division of integers. Take a dividend, a,
and divide it by the divisor, b,
to get some result that is a quotient,
q,
and a remainder, r,
if any. The modulus of a and b is the remainder, r.
This division theorem works for all numbers that are integers, provided b is
not zero.
If the a and b have the same sign (both
positive or both negative), the quotient is positive. If their signs are
opposite (one negative, one positive), the quotient is negative. What about the
modulus? It’s easy to think the same process applies, but does it? No.
To calculate r, use the division equation for
known values of a, b and q.
The following code in Visual C++ 2010 shows the four different
possibilities pos+/neg- values for a and b.
//
Header.
printf("Modulus With Negative Numbers\n\n");
printf("a x b = q + r OR b x q + r = a\n\n");
int a = 7;
int b = 2;
printf("a = %d, b = %d \n", a, b);
printf("q: %d / %d = %d \n", a, b, a / b);
printf("r: %d mod %d = %d \n", a, b, a % b);
// 2 x 3
+ 1 = 7
printf("%d x %d + %d = %d \n\n", b, a / b, a %
b, a);
a = -7;
b = 2;
printf("a = %d, b = %d \n", a, b);
printf("q: %d / %d = %d \n", a, b, a / b);
printf("r: %d mod %d = %d \n", a, b, a % b);
// 2 x
-3 - 1 = -7
printf("%d x %d + %d = %d \n\n", b, a / b, a %
b, a);
a = 7;
b = -2;
printf("a = %d, b = %d \n", a, b);
printf("q: %d / %d = %d \n", a, b, a / b);
printf("r: %d mod %d = %d \n", a, b, a % b);
// -2 x
-3 + 1 = 7
printf("%d x %d + %d = %d \n\n", b, a / b, a %
b, a);
a = -7;
b = -2;
printf("a = %d, b = %d \n", a, b);
printf("q: %d / %d = %d \n", a, b, a / b);
printf("r: %d mod %d = %d \n", a, b, a % b);
// -2 x
3 - 1 = -7
printf("%d x %d + %d = %d \n\n", b, a / b, a %
b, a);
Output.
You will get the same results in Visual Basic.
When it comes to using the modulus operator, test it with a
range of expected parameters to make sure it gives the result you expect and
want. Not all versions of C or C++ or other languages behave the same. If all
else fails, create your own modulus function to work the way you want.
No comments:
Post a Comment