Why does (360 / 24) / 60 = 0 … in Java

人走茶凉 提交于 2019-11-26 12:31:17
Jon Skeet

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.

You're actually doing integer division (JLS 15.17.2).

float div = ((360 / 24) / 60);
float div = (float) ((360 / 24) / 60);
float div = (float) (15 / 60);
float div = (float) (0);
float div = 0F;

To do floating point division, at least one of the operands need to be a floating point numeric type.

float div = ((360F / 24) / 60);
float div = 15F / 60;
float div = 0.25F;

Tip: if precision is important, you want to do as much of the calculation with double, before converting to float. In fact, unless your profiling demonstrates that you absolutely need float, you should always prefer double.

    float f;

    f = (1E-17F * 1E-17F);
    System.out.println(f); // prints "9.999999E-35"

    f = (float) (1E-17D * 1E-17D);
    System.out.println(f); // prints "1.0E-34"
wei2912

In your main method,

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

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:

-> 0 (integer value)

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:

public static void main(String[] args){
      float div = ((360.0 / 24.0) / 60.0);
      System.out.println(div);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!