如何使 2 个整数的除法产生一个浮点数而不是另一个整数? [英] How to make the division of 2 ints produce a float instead of another int?
问题描述
在另一个 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屋!