views:

321

answers:

2

I am trying to compute (360 / 24) / 60 I keep getting the answer 0.0 when I should get 0.25

In words: I want to divide 360 by 24 and then divide the result by 60

public class Divide {

public static void main(String[] args){
  float div = ((360 / 24) / 60);
  System.out.println(div);

}

}

This prints out:

0.0

Why is that? Am I doing something really stupid, or is there a good reason for this

+16  A: 

None of the operands in the arithmetic is a float - so it's all being done with integer arithmetic and then converted to a float. If you change the type of an appropriate operand to a float, it'll work fine:

float div = ((360 / 24f) / 60); // div is now 0.25

Note that if you changed just 60 to be a float, you'd end up with the 360 / 24 being performed as integer arithmetic - which is fine in this particular case, but doesn't represent what you I suspect you really intended. Basically you need to make sure that arithmetic operation is being performed in the way that you want.

Jon Skeet
More exact:360/24 = 1515/60 = 0Rounded always to integers ;)
TomTom
*sigh*. Monomorphic numeric literals confuse people. Polymorphic numeric literals confuse people. You just can't win.
jleedev
+16  A: 

You're actually doing integer division (JLS 15.17.2).

float div = ((360 / 24) / 60);
float div = (float) ((360 / 24) / 60);
float div = (float) (15 / 60);
float div = (float) (0);
float div = 0F;

To do floating point division, at least one of the operands need to be a floating point numeric type.

float div = ((360F / 24) / 60);
float div = 15F / 60;
float div = 0.25F;

Tip: if precision is important, you want to do as much of the calculation with double, before converting to float. In fact, unless your profiling demonstrates that you absolutely need float, you should always prefer double.

    float f;

    f = (1E-17F * 1E-17F);
    System.out.println(f); // prints "9.999999E-35"

    f = (float) (1E-17D * 1E-17D);
    System.out.println(f); // prints "1.0E-34"
polygenelubricants
don't you mean `double` in "In fact, you should probably use `float` almost always"?
Brandon Bodnár
Yeah, some typos. Fixed.
polygenelubricants