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
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:
Try:
Casting the ints to floats will allow floating-point division to take place.
You really only need to cast one, though.
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
To lessen the impact on code readabilty, I'd suggest:
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.
Try this: