Why am I getting different results for this but really they are the same numbers? [duplicate]
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
float answer = 5/2; and float answer 5.0/2.0;
When I add the decimal point 开发者_运维技巧I get 2.5 which is correct but without the decimal I get 2??
Integer division is different from floating point division. In your first example, you are dividing two integers, getting the result 2, and then assigning it to a float.
This is simple. 5/2 is evaluated according to integer division (since 5 and 2 are integers), the result is 2 (integer division gives the quotient, i.e. the division rounded down) and this is converted to a float. 5.0/2.0 does a floating-point division, so you get the correct answer of 2.5.
The reason this is happening is because when you are using 5 and 2, the numbers are being interpreted as integers, which also results in a rounded integer, which then casts to the float "answer". When you specify 5.0 and 2.0, these are considered floats, which allows the results to also be a float.
From the Java Documentation for numeric promotion : http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#239829
15.17.2 Division Operator /
The binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor. Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d·q||n|; moreover, q is positive when |n||d| and n and d have the same sign, but q is negative when |n||d| and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.
The result of 5/2 is an integer, your then casting that integer to a float during assignment.
Because the first one is based on integers. The division gets rounded to 2 because of it. Then it gets casted into float.
The second one is based on floats right from the start, so you get the correct answer.
you calculate in integers and use therefore integer arithmetics. The cast to float happens after the calculation. you could write
float answer = ((float) 5) / ((float) 2)
精彩评论