views:

94

answers:

6

Possible Duplicates:
Ints and Doubles doing division
1/252 = 0 in c#?

Hi,

Maybe because it's Friday, but I cannot understand this:

(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.

+8  A: 

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.

Tom Vervoort
sorry i didn't find it in the related ones... I'll take a deeper search now.
vtortola
http://stackoverflow.com/questions/3621674/1-252-0-in-c is the duplicate I was talking about. It was a bit hard to find through the search because of the not-very-descriptive title. :-)
Tom Vervoort
+1  A: 

Try (double)(1.0/2.0) - that will give the answer you expect.

open-collar
+2  A: 

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.

Simon
+1  A: 

As already written, the problem is the type. You can use suffixes to make sure the type is correct:

1d/2d=0.5
HCL
+2  A: 

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.

XstreamINsanity
+1  A: 
  1. (Double)1/2 = 0.5
  2. (Double)1/(Double)2 = 0.5
  3. (Double)((Double)1/(Double)2) = 0.5
  4. (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.

Vash