为什么 (360/24)/60 = 0 ... 在 Java 中 [英] Why does (360 / 24) / 60 = 0 ... in Java
问题描述
我正在尝试计算 (360/24)/60 当我应该得到 0.25 时,我不断得到答案 0.0
I am trying to compute (360 / 24) / 60 I keep getting the answer 0.0 when I should get 0.25
一句话:我想将 360 除以 24,然后将结果除以 60
In words: I want to divide 360 by 24 and then divide the result by 60
public class Divide {
public static void main(String[] args){
float div = ((360 / 24) / 60);
System.out.println(div);
}
}
打印出来:
0.0
这是为什么?我是在做一些非常愚蠢的事情,还是有充分的理由这样做
Why is that? Am I doing something really stupid, or is there a good reason for this
推荐答案
算术中的所有操作数都不是浮点数 - 所以这一切都是通过整数算术完成的,然后然后转换为浮点数.如果您将适当操作数的类型更改为浮点数,它会正常工作:
None of the operands in the arithmetic is a float - so it's all being done with integer arithmetic and then converted to a float. If you change the type of an appropriate operand to a float, it'll work fine:
float div = ((360 / 24f) / 60); // div is now 0.25
请注意,如果您仅将 60 更改为浮点数,则最终将 360/24 作为整数算术执行 - 在这种特殊情况下这很好,但并不代表我怀疑您真正想要的.基本上,您需要确保以您想要的方式执行算术运算.
Note that if you changed just 60 to be a float, you'd end up with the 360 / 24 being performed as integer arithmetic - which is fine in this particular case, but doesn't represent what I suspect you really intended. Basically you need to make sure that arithmetic operation is being performed in the way that you want.
这篇关于为什么 (360/24)/60 = 0 ... 在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!