Question

Here is the specific equation that's giving me 0 when it should be giving me -0.4 (-2/5)

slope2 = ((yVals[i+2] - originY) / (xVals[i+2] - originX));

(-2 - 0) / (2 + 3)

slope2 is a double

yVals[] is an int array

origin is an int

Why does it keep returning 0? I know the variables are being called correctly because I've done a println on the different vals and they are correct.

Was it helpful?

Solution

You are performing integer division in Java, where math done using ints must yield an int, so the division truncates anything beyond the decimal point. This means that in Java, -2 / 5 is 0. It's not enough that the target of the assignment is a double. One of the operands must be double (or float) to force floating-point arithmetic.

Cast one of the operands to the / operator to a double to force floating-point arithmetic.

slope2 = ( (double) (yVals[i+2] - originY) / (xVals[i+2] - originX));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top