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

In problem 3 of the prelab, you were asked to determine a possible source of error in the given program.  Perhaps, you have found that dividing two integers will not always result in the correct answer.  For example, that program produced 0 when you divide 2 by 4 as two integers.  There is a way to fix this problem temporarily, type casting that utilizes predefined functions.  Type casting allows us to change the type of a variable at the line where it is used. For example, in the program given in problem 3, one can change the variable type of the numerator (type cast) to float, so that the division will become a float divided by an integer.

#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;
// Just to show you that the type for 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 for 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 3.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 ex35.C.

#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