为什么 Java 中 (360 / 24) / 60 = 0 ...
我正在尝试计算 (360 / 24) / 60 当我应该得到 0.25 时我不断得到答案 0.0
换句话说:我想将 360 除以 24,然后将结果除以 60
public class Divide {
public static void main(String[] args){
float div = ((360 / 24) / 60);
System.out.println(div);
}
}
这打印出:
0.0
这是为什么呢?我是否做了一些非常愚蠢的事情,或者是否有充分的理由
I am trying to compute (360 / 24) / 60 I keep getting the answer 0.0 when I should get 0.25
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);
}
}
This prints out:
0.0
Why is that? Am I doing something really stupid, or is there a good reason for this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
算术中的操作数都不是浮点数 - 因此这一切都是通过整数算术完成的,然后转换为浮点数。如果将适当的操作数的类型更改为浮点型,它将正常工作:
请注意,如果您仅将 60 更改为浮点型,则最终会将 360 / 24 作为整数算术执行 - 这很好在这种特殊情况下,但并不代表我怀疑你的真正意图。基本上,您需要确保算术运算按照您想要的方式执行。
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:
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.
您实际上正在执行整数除法(JLS 15.17。 2)。
要进行浮点除法,至少有一个操作数需要是浮点数值类型。
提示:如果精度很重要,您需要在转换为
float
之前使用double
进行尽可能多的计算。事实上,除非您的分析表明您绝对需要float
,否则您应该始终更喜欢double
。You're actually doing integer division (JLS 15.17.2).
To do floating point division, at least one of the operands need to be a floating point numeric type.
Tip: if precision is important, you want to do as much of the calculation with
double
, before converting tofloat
. In fact, unless your profiling demonstrates that you absolutely needfloat
, you should always preferdouble
.在您的 main 方法中,
请注意 360、24 和 60 都是整数值。因此你会得到奇怪的值。
360/24 -> 360/24 15(非常好)
15 / 60 -> 0.4(浮点)
不幸的是,浮点数被截断,因此您得到:
然后,通过将 0 分配给浮点变量,您将 0 更改为浮点值 0.0。于是就有了这样的结果。
如果你想除以它们,你需要将它们更改为浮点值。
正确的代码应该是这样的:
In your main method,
Note that 360, 24 and 60 are all integer values. As such you will obtain weird values.
360/24 -> 15 (perfectly fine)
15 / 60 -> 0.4 (floating point)
Unfortunately for you floating point numbers are truncated thus you get:
Then, by assigning 0 to a floating point variable, you change 0 to a floating point value, 0.0. Thus the result.
If you want to divide them you need to change them into floating point values.
The correct code should be as such: