为什么(360/24)/ 60 = 0 ...在Java中 [英] Why does (360 / 24) / 60 = 0 ... in Java

查看:158
本文介绍了为什么(360/24)/ 60 = 0 ...在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算(360/24)/ 60当我得到0.25的时候,我总是得到答案0.0 bb b
我的理由是: 24然后将结果除以60 b

pre code $ public class Divide {

public static void main(String [] args){
float div =((360/24)/ 60);
System.out.println(div);


$ b $ / code $ / pre
$ b

打印出来:


0.0


我在做一些非常愚蠢的事情,或者有一个很好的理由

解决方案

算术中的操作数都不是float - 所有这些都是用整数算术完成的,然后然后转换成浮点数。如果你改变一个适当的操作数的类型为一个浮动,它会正常工作:
$ b $ pre $ float div =((360 / 24f)/ 60); // div现在是0.25

请注意,如果您将60更改为浮点数,最后360/24是作为整数算术运算的 - 在这个特殊情况下是好的,但并不代表我真正想要的东西。基本上你需要确保算术运算正在以你想要的方式执行。


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

解决方案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆