如何使2个整数的除法产生一个浮点而不是另一个整数? [英] How to make the division of 2 ints produce a float instead of another int?

查看:235
本文介绍了如何使2个整数的除法产生一个浮点而不是另一个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在计算速度的另一个Bruce Eckels练习中, v = s / t 其中s和t是整数。我怎么做才能让分部出现浮动?

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


推荐答案

首先将两个操作数中的一个投射到浮点数。

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.

编译器会有效地自动将另一个操作数转换为浮点数,因为规则说如果任一操作数是浮点类型,则操作将是浮点操作,即使另一个操作数是不可或缺的。 Java语言规范,§4.2。 4 §15.17

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

这篇关于如何使2个整数的除法产生一个浮点而不是另一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆