UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

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. For example: 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 <stdio.h> 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 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.


    CSEE | 201 | 201 F'98 | lectures | news | help

    Thursday, 10-Sep-1998 08:11:01 EDT