IdeaMonk

thoughts, ideas, code and other things...

Wednesday, June 06, 2007

What determines ouput (cast operators)

Okay, we know 5/4 = 1.25. So, if we have to do it in C, one would think of storing it in a float or double variable. i.e.

int i, j; double k; i = 5; j = 4;
k = i/j;
printf ("%lf" , k);

Now one would think that output will be 1.25. One would think that 5/4 equals 1.25 and since we are storing this result in a float type variable, it should be nicely done!
Alas! this won't happen because whenever an operation is performed, C takes into account the data-type of the operands. So the above code will assign 1 to k.
The solution to this is the cast operators. So using them we would have a modified code to get 1.25 as follows -
int i, j; double k; i = 5; j = 4;
k = (double) i / j;
printf ("%lf" , k);
or
int i, j; double k; i = 5; j = 4;
k = i / (double) j;
printf ("%lf" , k);
or even
int i, j; double k; i = 5; j = 4;
k = (double) i / (double) j;
printf ("%lf" , k);
All of these will give 1.25 as output. But the following won't -
    int i, j; double k; i = 5; j = 4;
k = (double) ( i / j );
printf ("%lf" , k);
Simply because i/j is being performed even before casting to double.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home