Activity  5-2 - Type Changing Functions (Type Casting)


We mentioned many times that dividing two integers will not always result in the correct answer.  For example, a program produces 0 when you divide 2 by 4 as two integers (instead of the expected 0.5).  There is a way to fix temporarily this problem by using type castingType casting changes the type of a variable at the line where it is used. In fact, one can change (type cast) the variable type of the numerator of the integer division to float, so that the division performs the division of a float divided by an integer. Here is an example:

//this program performs the division of two integers
#include<iostream>
using namespace std;

int main(void)
{
      int x,y;
      cout << "Enter 2 values for x and y separated by space, then press <Enter> :";
      cin >> x >> y;
      cout << endl;

      cout << "With type casting on x " << x << "/" << y << " = " << static_cast<float>(x)/y << endl;
      // Observe that the change of type of x is temporary
     // At the end of the statement the type of x is reset back to int again
      cout << "Right after type casting " << x << "/" << y << " = " << x/y << endl;

      return 0;
}

The change is shown in red font for clarity.  Note that variable x will stay an integer regardless of the static_cast<float>(x)/y statement.  Type casting will not change the type of x, instead static_cast<float>(x) is a function call to the predefined function static_cast<float with one argument, x, with the value returned that is of type float.   Thus, the division will be the float type value of x by the integer type value y, which results in a float value.

Exercise  5.5
The following program is supposed to convert a temperature in degree Fahrenheit to degree Celsius, but it will not produce the correct result.  Use type casting to fix the problem and run the program for the test values.  Call your new program ex55.cpp.

#include<iostream>
using namespace std;
int main( )
{
      int t_in_fah, t_in_cel;  //Notice that we declared these two as integers, not the best choice
      cout << "Enter a temperature in Fahrenheit \n";
      cin >> t_in_fah;

      t_in_cel = 5/9*(t_in_fah - 32);
      cout << "The temperature in Celsius is: " << t_in_cel << endl;

     return 0;
}

Test cases:

32 F is 0 C
212 F is 100 C