19

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;
}
roarknuppel
  • 249
  • 1
  • 2
  • 8
  • 2
    Google: integer division. It will give you an integer result with truncation. Write d = (double)w[L] /v[L]; – Bathsheba Sep 30 '13 at 09:18
  • Possible duplicate of [Why is the result of 1/3 == 0?](http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0) – fabian Mar 06 '16 at 20:34

3 Answers3

34

This line here d = w[L] /v[L]; takes place over several steps

d = (int)w[L]  / (int)v[L]
d=(int)(w[L]/v[L])            //the integer result is calculated
d=(double)(int)(w[L]/v[L])    //the integer result is cast to double

In other words the precision is already gone before you cast to double, you need to cast to double first, so

d = ((double)w[L])  / (int)v[L];

This forces java to use double maths the whole way through rather than use integer maths and then cast to double at the end

Richard Tingle
  • 15,728
  • 5
  • 47
  • 71
3

Actaully w[L]/v[L] here both are integer, on division operation it loose precision and trucated to integer value, latter trucated integer is converted to double.

Solution would be convert operand or divisor or both to double, division operaion would produce decimal value.

d = w[L]/(double)v[L];
Subhrajyoti Majumder
  • 38,572
  • 11
  • 72
  • 100
3

use like following

    d = (double) w[L]  /v[L];
stinepike
  • 50,967
  • 14
  • 89
  • 108