I can see this is a common problem for new programmers, however I didn't succeed in implementing any of the solution to my code. Basically I want to divide w and v, which must be saved to a double variable. But it prints [0.0, 0.0, ... , 0.0]
public static double density(int[] w, int[] v){
double d = 0;
for(L = 0; L < w.length; L++){
d = w[L] /v[L];
}
return d;
}
This line here
d = w[L] /v[L];
takes place over several stepsIn other words the precision is already gone before you cast to double, you need to cast to double first, so
This forces java to use double maths the whole way through rather than use integer maths and then cast to double at the end
Actaully
w[L]/v[L]
here both are integer, on division operation it loose precision and trucated tointeger
value, latter trucatedinteger
is converted todouble
.Solution would be convert operand or divisor or both to double, division operaion would produce decimal value.
use like following