Fahrenheit to Celsius

Here's the next problem to show problems when dealing with number of both types int and float.

Problem:

The equation to convert temperature in degrees Fahrenheit to temperature in degrees celsius is: C = ( 5 / 9 ) ( F - 32 ) , where C is degrees Celsius and F is degrees Fahrenheit. Write a program which calculates and prints the Celsius equivalent of an entered number for degrees Fahrenheit.

Solution:


#include <iostream>

int main()
{
   float fahren = 0;
   float celsius = 0;
   
   cout << "Enter degrees fahrenheit: ";
   cin >> fahren;
   
   celsius = (5.0 / 9.0) * (fahren - 32);

   cout << "That is " << celsius << " degrees celsius." << endl;
   
   return 0;
}

Here we see nothing new. One item to note before getting into the lesson of this problem is:

   float fahren = 0;
   float celsius = 0; 

A good habit is to always initialize your variables to 0 in order to avoid unpredictable results. When memory is allocated for a variable, there is no telling what was in that memory position prior to your program's allocating it. Therefore, if you do not initialize it as you define it, you may forget later on. If that happens and you try to do a calculation with this unknown value, you will get very unpredictable, very bad results.

This can also be accomplished by defining the variable and then initializing it at a later time, but not in as good form:

   float celsius;
   celsius = 0;

But... the point of this problem is to demonstrate this line:

   celsius = (5.0 / 9.0) * (fahren - 32);

When dividing integers in C++, you get an integer value back. Therefore, dividing the integers 5 by 9, you would get back the integer 0. Here we want to inform the compiler what it is that we want exactly: we want it to use the float values 5.0 and 9.0. Without doing this, this calculation would result in zero for every input (zero times anything is always zero).

If you are dividing two integer variables, you must also do this to inform the compiler. Take this code fragment for example:

   float celsius;
   int five;
   int nine;

   five = 5;
   nine = 9;

   celsius = five / nine;

You would get a result of zero. In the instance of using variables, you should "cast" one integer into a float value by either:

   celsius = float(five) / nine;

or:

   celsius = static_cast<float>(five) / nine;

This makes a temporary variable for five that is of a float type. Since in C++ you cannot divide a float by an integer, the compiler will automatically "upgrade", formally known as a promote, the variable nine to a float to match the cast for five, and then will put the resulting float into the variable celsius.

Note, you cannot automatically "downgrade", or demote, a type like
this, it only works one way.

Now let's look at the Orders of Operations in C++.