### 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;or

k = (double) i / j;

printf ("%lf" , k);

int i, j; double k; i = 5; j = 4;or even

k = i / (double) j;

printf ("%lf" , k);

int i, j; double k; i = 5; j = 4;All of these will give 1.25 as output. But the following won't -

k = (double) i / (double) j;

printf ("%lf" , k);

int i, j; double k; i = 5; j = 4;Simply because i/j is being performed even before casting to double.

k = (double) ( i / j );

printf ("%lf" , k);

Labels: programming

## 0 Comments:

## Post a Comment

Subscribe to Post Comments [Atom]

<< Home