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:00

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;
查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 14:01

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.

查看更多
冷夜・残月
4楼-- · 2018-12-31 14:07

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:

1. v = (float)s / t;
2. v = (float)s / (float)t;
查看更多
墨雨无痕
5楼-- · 2018-12-31 14:08

To lessen the impact on code readabilty, I'd suggest:

v = 1d* s/t;
查看更多
若你有天会懂
6楼-- · 2018-12-31 14:10

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.

查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 14:21

Try this:

class CalcV 
{
      float v;
      float calcV(int s, int t)
      {
          float value1=s;
          float value2=t;
          v = value1 / value2;
          return v;
      } //end calcV
}
查看更多
登录 后发表回答