double x;
x = 24.0 / 0;
System.out.println(x);
The code above simply prints the word "Infinity", whilst the code below throws the exception...
int y;
y = 24 / 0;
System.out.println(y);
Why this is, I guess, is down to the definition of a double. Note that x is a number and hence:
if (Double.isNaN(x)) {
System.out.println("x is not a number");
}
will not print anything. To detect a divide by zero using floating point arithmetic, you need to check for infinity:
if (Double.isInfinite(x)) {
System.out.println("x is infinite");
}
No comments:
Post a comment