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.
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
Test mixing floating-point and integer types.
*/
#include
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 variable */
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) ;
}
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:
quotient = numerator / (double) 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.