在 Bruce Eckels 计算速度的另一项练习中,v = s/t
其中 s 和 t 是整数。我怎样才能让该部门制造出一个花车?
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
最佳答案
首先将两个操作数之一转换为 float 。
v = (float)s / t;
Actor 阵容更高precedence比除法更重要,所以发生在除法之前。
另一个操作数将被编译器有效地自动转换为浮点型,因为规则规定,如果任一操作数是浮点类型,则即使另一个操作数是整数,该操作也将是浮点操作。 Java Language Specification, §4.2.4和 §15.17
关于java - 如何使 2 个整数相除产生一个 float 而不是另一个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235055/