Problem with Double and division [duplicate]
Possible Duplicates:
Ints and Doubles doing division 1/252 = 0 in c#?
Hi,
Maybe because it's Friday, but I cannot understand 开发者_StackOverflowthis:
(Double)1/2 = 0.5
(Double)1/(Double)2 = 0.5
(Double)((Double)1/(Double)2) = 0.5
(Double)(1/2) = 0.0
Why the last operation is 0? :S
Kind regards.
Because 1 and 2 are integers. The result is 0. If you cast that to a double, it's still 0. This question was asked just a couple of days ago.
If you divide two ints, then the result will also be int. So 1/2 gives you a zero which is an integer. Then you are casting 0 to double, which is still zero.
Everyone's given you the correct answer so far, I'm adding this so other readers don't miss it in the comments.
Use the same rule as regular math. Inner Parenthesis first. So in the first example, the 1 is casted to a double before the division occurs, making the result a double (division of int and double results in double). This rings true if it is (Double)1/2
or 1/(Double)2
. So in the last example, (Double)(1/2)
, the (1/2)
is performed first, int on int, resulting in int. Then the (Double) casts it to a Double. Hope this not only helps you but anyone else curious about this question. I myself have had many times where I had a long equation and literally had to cast each parameter of the equation to a double.
Try (double)(1.0/2.0) - that will give the answer you expect.
As already written, the problem is the type. You can use suffixes to make sure the type is correct:
1d/2d=0.5
(Double)1/2 = 0.5
(Double)1/(Double)2 = 0.5
(Double)((Double)1/(Double)2) = 0.5
(Double)(1/2) = 0.0
In first three cases You cast the integer value (thas is default type for number when you do not use suffix or does not contain dot ) to Double and then do the division with an integer value in first case and with double for 2 and 3, in contrast to last (4) case where the brackets change the order of operation first You divide two integers, and after that cast the result to Double.
精彩评论