tags:

views:

956

answers:

6

In another Bruce Eckels exercise in calculating velocity, v = s / t where s and t are integers. How do I make it so the division cranks out a float?

class CalcV {
  float v;
  float calcV(int s, int t) {
    v = s / t;
    return v;
  } //end calcV
}

public class PassObject {

  public static void main (String[] args ) {
    int distance;
    distance = 4;

    int t;
    t = 3;

    float outV;

    CalcV v = new CalcV();
    outV = v.calcV(distance, t);

    System.out.println("velocity : " + outV);
  } //end main
}//end class
+15  A: 

Just cast one of the two operands to a float first.

v = (float)s / t;

The cast has higher precedence than the division, so happens before the division.

The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4

Alnitak
+2  A: 

You can cast the numerator or the denominator to float...

int operations usually return int, so you have to change one of the operanding numbers.

Jhonny D. Cano -Leftware-
Usually? If they return at all, they're going to return int.
Matthew Flaschen
+5  A: 

Try:

v = (float)s / (float)t;

Casting the ints to floats will allow floating-point division to take place.

You really only need to cast one, though.

Patrick McCafferty
+2  A: 

Cast one of the integers to a float to force the operation to be done with floating point math. Otherwise integer math is always preferred. So:

v = (float)s / t;
Jason Coco
+1  A: 

You can cast even just one of them, but for consistency you may want to explicitly cast both so something like v = (float)s / (float)t should work.

Uri
A: 

In addition to the other answers:

Always use double for floating point computation.*

*Unless there is a specific need to use float, e.g. to save memory or speed up computation.

starblue