How to make the division of 2 ints produce a float

2018-12-31 13:35发布

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

标签: java
9条回答
无色无味的生活
2楼-- · 2018-12-31 14:23

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 and §15.17

查看更多
梦该遗忘
3楼-- · 2018-12-31 14:24

JLS Standard

JLS 7 15.17.2. Division Operator / says:

Integer division rounds toward 0.

This is why 1/2 does not give a float.

Converting just either one to float as in (float)1/2 suffices because 15.17. Multiplicative Operators says:

Binary numeric promotion is performed on the operands

and 5.6.2. Binary Numeric Promotion says:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float
查看更多
何处买醉
4楼-- · 2018-12-31 14:27

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.

查看更多
登录 后发表回答