< previous page page_67 next page >

Page 67
LISTING 5.2 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
12:        cout << \nHere's the temperature in Celsius: ;
13:        cout << TempCel << endl;
14:        return 0;
15:      }
16:
17:      float Convert(float TempFer)
18:      {
19:        float TempCel;
20:        TempCel = ((TempFer - 32) * 5) / 9;
21:        return TempCel;
22:      }

Output:
Please enter the temperature in Fahrenheit: 212
Here's the temperature in Celsius: 100

Please enter the temperature in Fahrenheit: 32
Here's the temperature in Celsius: 0

Please enter the temperature in Fahrenheit: 85
Here's the temperature in Celsius: 29.4444
Analysis: On lines 6 and 7, two float variables are declared, one to hold the temperature in Fahrenheit and one to hold the temperature in degrees Celsius. The user is prompted to enter a Fahrenheit temperature on line 9, and that value is passed to the function Convert().
Execution jumps to the first line of the function Convert() on line 19, where a local variable, also named TempCel, is declared. Note that this local variable is not the same as the variable TempCel on line 7. This variable exists only within the function Convert(). The value passed as a parameter, TempFer, is also just a local copy of the variable passed in by main().
This function could have named the parameter FerTemp and the local variable CelTemp, and the program would work equally well. You can reenter these names and recompile the program to see this work.
The local function variable Tempcel is assigned the value that results form subtracting 32 from the parameter TempFer, multiplying by 5, and then dividing by 9. This value is then returned as the return value of the function, and on line 11 it is assigned to the variable TempCel in the main() function. It is printed on line 13.
The program is run three times. The first time the value 212 is passed in to ensure that the boiling point of water in degrees Fahrenheit (212) generates the correct answer in degrees Celsius (100). The second test is the freezing point of water. The third test is a random number chosen to generate a fractional result.

 
< previous page page_67 next page >

If you like this book, buy it!