Sams Teach Yourself C++ in 21 Days

(singke) #1
Local variables are defined the same as any other variables. The parameters passed in to
the function are also considered local variables and can be used exactly as if they had
been defined within the body of the function. Listing 5.2 is an example of using parame-
ters and locally defined variables within a function.

LISTING5.2 The Use of Local Variables and Parameters
1: #include <iostream>
2:
3: float Convert(float);
4: int main()
5: {
6: using namespace std;
7:
8: float TempFer;
9: float TempCel;
10:
11: cout << “Please enter the temperature in Fahrenheit: “;
12: cin >> TempFer;
13: TempCel = Convert(TempFer);
14: cout << “\nHere’s the temperature in Celsius: “;
15: cout << TempCel << endl;
16: return 0;
17: }
18:
19: float Convert(float TempFer)
20: {
21: float TempCel;
22: TempCel = ((TempFer - 32) * 5) / 9;
23: return TempCel;
24: }

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
On lines 8 and 9, two floatvariables 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 11, and that value is passed to the
function Convert()on line 13.

OUTPUT


106 Day 5


ANALYSIS
Free download pdf