Question

public double[] deel(int[] rij1, int[] rij2)
    {
        final int RIJ_LENGTH = 5;
        double rij[] = new double [RIJ_LENGTH];

        for (int i = 0; i < rij.length; i++)
            rij[i] = (double) (rij1[i]/rij2[i]);



return rij;
}

This is a method for creating a new array called 'rij'. This new array has as elements (rij1 / rij2). So rij[0] = rij1[0]/rij2[0]

But when I try to run this code, it says error: "/ by zero"

Please help me.

Was it helpful?

Solution

Your arrays are of integers and dividing an integer by zero is undefined. You would need to check the array element is non-zero before dividing by the element and decide what value your result should take in the event that the denominator is zero. Also note that your output array is a double array, but you will lose precision in your data as the arguments are int arrays and integer division works very differently to floating point division - the result of an integer divided by an integer is another integer, not a double. To get the behaviour you want you should cast the numerator or denominator to a double, not the result as this simply casts the integer result after the integer division has taken place. If you are new to programming, google for integer division or search for some stackoverflow questions dealing with integer division.

EDIT: In light of your comment, this line

rij[i] = (double) (rij1[i]/rij2[i]);

should be

rij[i] = ((double)rij1[i]) / rij2[i];   

(or you could casting denominator to double instead - or even both) in order to prevent errors with integer division. Your error is telling you you are dividing by zero which suggests rij2[i] is zero for some value of i. You need to detect this in your code. If you are certain ALL elements are strictly greater than zero, then I would suggest you perhaps have an error elsewhere where some other code is overwriting these values. Either way, you could step through with the debugger or add some error catch code to make absolutely certain. I cannot "just edit" your code to avoid a division by zero if you are actually dividing by zero!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top