<< Chapter < Page | Chapter >> Page > |
C. -0.010999999999999996
Modulus operator can be used with floating types
In this case, the program returns the remainder that would be produced by dividing a double value of -0.11 by a double value of 0.033 and terminating thedivide operation at the beginning of the fractional part of the quotient.
Say that again
Stated differently, the result of the modulus operation is the remainder that results after
Modulus result is not exact
According to my hand calculator, taking into account the fact that the left operand is negative, this operation should produce a modulus result of-0.011. As you can see, the result produced by the application of the modulus operation to floating types is not exact.
B. Runtime Error
Integer modulus involves integer divide
The modulus operation with integer operands involves an integer divide.
Therefore, it is subject to the same kind of problem as an ordinary integer divide when the right operand has a value of zero.
Program produces a runtime error
In this case, the program produced a runtime error that terminated the program. The error produced by JDK 1.3 is as follows:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Worker.doMod(Ap020.java:14)at Ap020.main(Ap020.java:6) |
Dealing with the problem
As with integer divide, you can either test the right operand for a zero value before performing the modulus operation, or you can deal with the problemafter the fact using try-catch.
D. -2
What is a modulus operation?
In elementary terms, we like to say that the modulus operation returns the remainder that results from a divide operation.
In general terms, that is true.
Some interesting behavior
However, the modulus operation has some interesting behaviors that are illustrated in this and the next several questions.
This program returns the modulus of -11 and 3, with -11 being the left operand.
What is the algebraic sign of the result?
Here is a rule:
The result of the modulus operation takes the sign of the left operand, regardless of the sign of the quotient and regardless of the sign of theright operand. In this program, that produced a result of -2.
Changing the sign of the right operand would not have changed the sign of the result.
Exercise care with sign of modulus result
Thus, you may need to exercise care as to how you interpret the result when you perform a modulus operation having a negative left operand.
C. Infinity
Floating divide by zero
This program attempts to divide the double value of 11 by the double value of zero.
No runtime error with floating divide by zero
In the case of floating types, an attempt to divide by zero does not produce a runtime error. Rather, it returns a value that the println method interprets and displays as Infinity.
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?