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