Mixing Types
Mixing types can lead to strange results.
Generally, if a binary operator is used on both an integer and
a double, the integer is converted to a double and the result is a
double. Why?
For example:
- Dividing a 9.0 by 4 gives the double value 2.25
- Dividing 9 by 4 gives the integer value 2
But consider:
/*****************************************
Program: mix.c
Author: Richard Chang
Date: ?
Revised by: Sue Bogar
Date revised: 2/2/98
Section: 101
E-Mail: bogar@cs.umbc.edu
This program illustrates possible problems
when mixing floating-point and integer types
*****************************************/
#include
int main()
{
double x ;
int i ;
/* A floating-point constant assigned to an integer variable*/
i = 2.7 ;
printf("i = %d\n", i) ;
/* An integer constant assigned to a double */
x = 3 + 4 ;
printf("x = %f\n", x) ;
/* Mixing doubles and integers results in a double */
printf("\n") ;
printf("9.0/4.0: %f\n\n", 9.0/4.0) ;
printf(" 9/4.0: %f\n\n", 9/4.0) ;
printf(" 9.0/4: %f\n\n", 9.0/4) ;
/* A nasty surprise, integer division */
printf("9/4 printed using %%f: %f\n\n", 9/4) ;
/* More nasty surprises*/
x = 9/4 ;
printf("9/4 assigned into a double and printed with %%f: %f\n\n", x) ;
return 0;
}
Which results in:
i = 2
x = 7.000000
9.0/4.0: 2.250000
9/4.0: 2.250000
9.0/4: 2.250000
9/4 printed using %f: 0.000000
9/4 assigned into a double and printed with %f: 2.000000
Type casting
You can explicitly convert a value of an expression to a specific type
via a type cast operator
( <type name> ) <expression>
For example:
int numerator, denominator;
double quotient;
/* these statements produce the desired affect */
quotient = numerator / (double) denominator;
quotient = (double)numerator / denominator;
/* but this one does not... why? */
quotient = (double)(numerator / denominator);
where numerator and denominator are both integers and quotient is a
double, casting one of the integer variables to a double prevents integer
division and causes the answer to be a double, then assigns that answer
into the variable quotient.