3 Replies Latest reply: Aug 14, 2009 12:59 PM by 796447

Casting question

What is the difference between this:
``int value = ((int)(double)((intVar1/intVar2)*100));``
and
``````double d = ((double)intVar1/intVar2)*100;
int value = (int)d;``````
?

The first one allways produces zero.
The second one allways prints a value greater than zero.

How come?
• 1. Re: Casting question
The first one does integer division (intVar1/intVar2), which always produces an integer result. Then this is multiplied by 100, then cast to a double, then cast back to an int.

The second one first casts intVar1 to a double, then divides by intVar2. A double divided by an int is a double. Then you take it from there.

Note: It has nothing to do with splitting it into two statements. The placement of the parens is different in the two examples, and hence the order of operations changed, and that's what makes the difference.
• 2. Re: Casting question
warnerja wrote:
Note: It has nothing to do with splitting it into two statements. The placement of the parens is different in the two examples, and hence the order of operations changed, and that's what makes the difference.
However, if the OP would've taken the time to break them each down into individual operations, and look at the intermediate results, he'd have at least gotten some idea of what was going on before posting here.
• 3. Re: Casting question
jverd wrote:
However, if the OP would've taken the time to break them each down into individual operations, and look at the intermediate results, he'd have at least gotten some idea of what was going on before posting here.
Very true. @OP, lesson learned hopefully.