简体   繁体   中英

Java: How to divide arrays and use Double.NaN?

I am working on an assignment using arrays. Typical calculator assignment. Now, I am having some issue with my division of arrays. You can't (well you really can) divide by zero. So if I take 2 arrays and divide them, I want to use Double.Nan. See my example:

 double[] array1 = {2, 4, 6}

 double[] array2 = {2, 2, 0}

 public static double[] divide(double[] operand1, double[] operand2) {

    double[] divArray = new double[operand1.length];

    for(int i = 0; i < operand1.length; i++) {
        if (operand2[i] == 0) {
            divArray[i] = Double.NaN;
        } else {
            divArray[i] = operand1[i] / operand2[i];
        }           
    }

    return divArray;
}

(the divArray is returned to the main method)

After looping through to output the new array, I end up with this...

[1.0, 2.0, 0.0]

How come the 0.0 is not NaN?

Also, how can I make some adjustments to be able to have it output NaN?

For bonus points, adding to the answer from Andreas above...

for(int i = 0; i < operand1.length; i++) {
    divArray[i] = (operand2[i] == 0.0) ? Double.NaN : (operand1[i] / operand2[i]);
}

Probably don't need either set of parenthesis, but I like them just for clarity. Also, because it's doubles, I used a 0.0 in the check, although also probably not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM