• Type Casting

    What is type casting?

    • changing the type of a variable's value temporarily to perform an operation
    • the variable is unchanged after the operation and type casting

    Why is type casting important?

    • you don't need a separate variable to hold the same value but in a different type
      • e.g. variable_as_int = 1 and variable_as_float = 1.0
    • you can specify a data type that you need at the time of the operation, e.g. this gives you flexibility

    How to type cast?

  • Type Cast Example

    type_casting.c:

    Things to note:

    • going from a float to an int truncates the decimals
      • it might be unclear whether you were expecting the float to be truncated or to be rounded
      • it might be unclear if the truncating behavior in your program was an oversight (e.g. a bug) or if it was intentional
      • it's good practice to be explicit in your code, e.g. use a truncating or rounding function
    • type casting an int to a float is not necessary if you're performing an operation with another float
      • C makes some of these assumptions for you
      • be sure you know what C will do before using it
  • Where to Type Cast?

    type_casting_trivia.c:

    Fix this program that is trying to calculate $z={-x+(x^2-4y)}/{2y}$

      Test inputs and outputs:
    • x = 100; y = 50; z = 97.0;
    • x = 100; y = 80; z = 59.875;

    where_to_type_cast.c:

  • Assignment

    Homework Problem 13.1, at the end of this problem you should submit to Laulima:

    • a file named UHusername_13_1.c
      • example:
      • zhaol_13_1.c
    • update fix_me.c to output the correct value:

      the expressions integer1/decimal and integer1/integer2 should not be modified for this exercise

    • Test Case 1:
      int / float: 0.750000
      int / int: 0.750000
      using the % operator: 1