Applying casts to the results of integer and floating point division: what's going on here?

后端 未结 4 1051
情话喂你
情话喂你 2021-01-18 17:49

I\'m a beginner and there\'s something that\'s not making much sense to me. Please could be so kind as to explain where I\'m going wrong. I\'m sorry if this has been asked b

4条回答
  •  心在旅途
    2021-01-18 17:52

    This is specified in the Java Language Specification - Numeric Promotions

    If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed.

    Then:

    If either operand is of type double, the other is converted to double.

    Otherwise, if either operand is of type float, the other is converted to float.

    Otherwise, if either operand is of type long, the other is converted to long.

    Otherwise, both operands are converted to type int.

    The concept is called widening conversion:

    5.1.2 Widening Primitive Conversion

    The following 19 specific conversions on primitive types are called the widening primitive conversions:

    • byte to short, int, long, float, or double
    • short to int, long, float, or double
    • char to int, long, float, or double
    • int to long, float, or double
    • long to float or double float to double

    The reason why

    (int) (1.0/3) == 0
    

    is because you cast the result of 1.0/3 (0.33333... by the above rules) explicitly to an integer, which is equivalent to "floor(result)" (rounding down), so the result is 0.

    Cast has a higher precedence than /, that's why the other operations were misleading to your understanding:

    (double) 1 / 3
    

    will explicitly cast 1 to a double value 1.0 first, so again the result by the above rules is equal to 0.3333....

提交回复
热议问题