Tải bản đầy đủ (.pdf) (10 trang)

Absolute C++ (4th Edition) part 11 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (171.18 KB, 10 trang )

102 Function Basics
produced by another form of scaling. The following generates a pseudorandom floating-
point value between
0.0 and 1.0:
rand( )/static_cast<double>(RAND_MAX)
The type cast is made so that we get floating-point division rather than integer division.
Display 3.4 A Function Using a Random Number Generator
(part 1 of 2)
1 #include <iostream>
2 #include <cstdlib>
3 using namespace std;
4 int main( )
5 {
6 int month, day;
7 cout << "Welcome to your friendly weather program.\n"
8 << "Enter today’s date as two integers for the month and the day:\n";
9 cin >> month;
10 cin >> day;
11 srand(month*day);
12 int prediction;
13 char ans;
14 cout << "Weather for today:\n";
15 do
16 {
17 prediction = rand( ) % 3;
18 switch (prediction)
19 {
20 case 0:
21 cout << "The day will be sunny!!\n";
22 break;
23 case 1:


24 cout << "The day will be cloudy.\n";
25 break;
26 case 2:
27 cout << "The day will be stormy!\n";
28 break;
29 default:
30 cout << "Weather program is not functioning properly.\n";
31 }
32 cout << "Want the weather for the next day?(y/n): ";
33 cin >> ans;
34 } while (ans == 'y' || ans == 'Y');
35 cout << "That's it from your 24-hour weather program.\n";
36 return 0;
37 }
Programmer-Defined Functions 103
Self-Test Exercises
5. Give an expression to produce a pseudorandom integer number in the range 5 to 10
(inclusive).
6. Write a complete program that asks the user for a seed and then outputs a list of ten ran-
dom numbers based on that seed. The numbers should be floating-point numbers in the
range
0.0 to 1.0 (inclusive).
Programmer-Defined Functions
A custom-tailored suit always fits better than one off the rack.
My uncle, the tailor
The previous section told you how to use predefined functions. This section tells you
how to define your own functions.

DEFINING FUNCTIONS THAT RETURN A VALUE
You can define your own functions, either in the same file as the main part of your pro-

gram or in a separate file so that the functions can be used by several different programs.
Display 3.4 A Function Using a Random Number Generator
(part 2 of 2)
S
AMPLE
D
IALOGUE
Welcome to your friendly weather program.
Enter today’s date as two integers for the month and the day:
2 14
Weather for today:
The day will be cloudy.
Want the weather for the next day?(y/n): y
The day will be cloudy.
Want the weather for the next day?(y/n): y
The day will be stormy!
Want the weather for the next day?(y/n): y
The day will be stormy!
Want the weather for the next day?(y/n): y
The day will be sunny!!
Want the weather for the next day?(y/n): n
That's it from your 24-hour weather program.
3.2
104 Function Basics
The definition is the same in either case, but for now we will assume that the function
definition will be in the same file as the
main part of your program. This subsection dis-
cusses only functions that return a value. A later subsection tells you how to define
void functions.
Display 3.5 contains a sample function definition in a complete program that demon-

strates a call to the function. The function is called
totalCost and takes two arguments—
the price for one item and the number of items for a purchase. The function returns
the total cost, including sales tax, for that many items at the specified price. The func-
tion is called in the same way a predefined function is called. The definition of the
function, which the programmer must write, is a bit more complicated.
The description of the function is given in two parts. The first part is called the
function declaration or function prototype. The following is the function declara-
tion (function prototype) for the function defined in Display 3.5:
double totalCost(int numberParameter, double priceParameter);
The first word in a function declaration specifies the type of the value returned by the
function. Thus, for the function
totalCost, the type of the value returned is double.
Next, the function declaration tells you the name of the function; in this case,
total-
Cost
. The function declaration tells you (and the compiler) everything you need to
know in order to write and use a call to the function. It tells you how many arguments
the function needs and what type the arguments should be; in this case, the function
totalCost takes two arguments, the first one of type int and the second one of type
double. The identifiers numberParameter and priceParameter are called formal param-
eters, or parameters for short. A formal parameter is used as a kind of blank, or place-
holder, to stand in for the argument. When you write a function declaration, you do
not know what the arguments will be, so you use the formal parameters in place of the
arguments. Names of formal parameters can be any valid identifiers. Notice that a
function declaration ends with a semicolon.
Although the function declaration tells you all you need to know to write a function
call, it does not tell you what value will be returned. The value returned is determined
by the function definition. In Display 3.3 the function definition is in lines 24 to 30 of
the program. A function definition describes how the function computes the value it

returns. A function definition consists of a function header followed by a function body.
The function header is written similar to the function declaration, except that the
header does not have a semicolon at the end. The value returned is determined by the
statements in the function body.
The function body follows the function header and completes the function defini-
tion. The function body consists of declarations and executable statements enclosed
within a pair of braces. Thus, the function body is just like the body of the
main part of
a program. When the function is called, the argument values are plugged in for the for-
mal parameters, and then the statements in the body are executed. The value returned
by the function is determined when the function executes a
return statement. (The
details of this “plugging in” will be discussed in Chapter 4.)
function
declaration or
function
prototype
type for
value returned
formal
parameter
function
definition
function
header
function body
Programmer-Defined Functions 105
Display 3.5 A Function Using a Random Number Generator
(part 1 of 2)
1 #include <iostream>

2 using namespace std;
3 double totalCost(int numberParameter, double priceParameter);
4 //Computes the total cost, including 5% sales tax,
5 //on numberParameter items at a cost of priceParameter each.
6 int main( )
7 {
8 double price, bill;
9 int number;
10 cout << "Enter the number of items purchased: ";
11 cin >> number;
12 cout << "Enter the price per item $";
13 cin >> price;
14 bill = totalCost(number, price);
15 cout.setf(ios::fixed);
16 cout.setf(ios::showpoint);
17 cout.precision(2);
18 cout << number << " items at "
19 << "$" << price << " each.\n"
20 << "Final bill, including tax, is $" << bill
21 << endl;
22 return 0;
23 }
24 double totalCost(int numberParameter, double priceParameter)
25 {
26 const double TAXRATE = 0.05; //5% sales tax
27 double subtotal;
28 subtotal = priceParameter * numberParameter;
29 return (subtotal + subtotal*TAXRATE);
30 }
S

AMPLE
D
IALOGUE
Enter the number of items purchased: 2
Enter the price per item: $10.10
2 items at $10.10 each.
Final bill, including tax, is $21.21
Function declaration;
also called the function
prototype
Function call
Function
body
Function
definition
Function
head
106 Function Basics
A return statement consists of the keyword return followed by an expression. The
function definition in Display 3.5 contains the following
return statement:
return (subtotal + subtotal*TAXRATE);
When this return statement is executed, the value of the following expression is
returned as the value of the function call:
(subtotal + subtotal*TAXRATE)
The parentheses are not needed. The program will run the same if the parentheses are
omitted. However, with longer expressions, the parentheses make the
return statement
easier to read. For consistency, some programmers advocate using these parentheses
even with simple expressions. In the function definition in Display 3.3 there are no

statements after the
return statement, but if there were, they would not be executed.
When a
return statement is executed, the function call ends.
Note that the function body can contain any C++ statements and that the state-
ments will be executed when the function is called. Thus, a function that returns a
value may do any other action as well as return a value. In most cases, however, the
main purpose of a function that returns a value is to return that value.
Either the complete function definition or the function declaration (function proto-
type) must appear in the code before the function is called. The most typical arrange-
ment is for the function declaration and the
main part of the program to appear in one
or more files, with the function declaration before the
main part of the program, and
for the function definition to appear in another file. We have not yet discussed dividing
a program across more than one file, and so we will place the function definitions after
the
main part of the program. If the full function definition is placed before the main
part of the program, the function declaration can be omitted.

ALTERNATE FORM FOR FUNCTION DECLARATIONS
You are not required to list formal parameter names in a function declaration (function
prototype). The following two function declarations are equivalent:
double totalCost(int numberParameter, double priceParameter);
and
double totalCost(int, double);
We will usually use the first form so that we can refer to the formal parameters in the
comment that accompanies the function declaration. However, you will often see the
second form in manuals.
This alternate form applies only to function declarations. A function definition must

always list the formal parameter names.
return
statement
Programmer-Defined Functions 107
Example
Pitfall
Pitfall
A
RGUMENTS

IN

THE
W
RONG
O
RDER
When a function is called, the computer substitutes the first argument for the first formal param-
eter, the second argument for the second formal parameter, and so forth. Although the computer
checks the type of each argument, it does not check for reasonableness. If you confuse the order
of the arguments, the program will not do what you want it to do. If there is a type violation due
to an argument of the wrong type, then you will get an error message. If there is no type viola-
tion, your program will probably run normally but produce an incorrect value for the value
returned by the function.
U
SE

OF

THE

T
ERMS

P
ARAMETER

AND

A
RGUMENT
The use of the terms
formal parameter
and
argument
that we follow in this book is consistent with
common usage, but people also often use the terms
parameter
and
argument
interchangeably.
When you see the terms
parameter
and
argument,
you must determine their exact meaning from
context. Many people use the term
parameter
for both what we call
formal parameters
and what

we call
arguments
. Other people use the term
argument
both for what we call
formal parameters

and what we call
arguments
. Do not expect consistency in how people use these two terms. (In
this book we sometimes use the term
parameter
to mean
formal parameter
, but this is more of an
abbreviation than a true inconsistency.)

FUNCTIONS CALLING FUNCTIONS
A function body may contain a call to another function. The situation for these sorts of
function calls is the same as if the function call had occurred in the
main part of the
program; the only restriction is that the function declaration (or function definition)
must appear before the function is used. If you set up your programs as we have been
doing, this will happen automatically, since all function declarations come before the
main part of the program and all function definitions come after the main part of the
program. Although you may include a function call within the definition of another
function, you cannot place the definition of one function within the body of another
function definition.
A R
OUNDING

F
UNCTION
The table of predefined functions (Display 3.2) does not include any function for rounding a
number. The functions
ceil and floor are almost, but not quite, rounding functions. The func-
tion
ceil always returns the next-highest whole number (or its argument if it happens to be a
whole number). So,
ceil(2.1) returns 3.0, not 2.0. The function floor always returns the
nearest whole number less than (or equal to) the argument. So,
floor(2.9) returns 2.0, not
108 Function Basics
3.0. Fortunately, it is easy to define a function that does true rounding. The function is defined
in Display 3.6. The function
round rounds its argument to the nearest integer. For example,
round(2.3) returns 2, and round(2.6) returns 3.
To see that
round works correctly, let’s look at some examples. Consider round(2.4). The value
returned is the following (converted to an
int value):
floor(2.4 + 0.5)
which is floor(2.9), or 2.0. In fact, for any number that is greater than or equal to 2.0 and
strictly less than
2.5, that number plus 0.5 will be less than 3.0, and so floor applied to that
number plus
0.5 will return 2.0. Thus, round applied to any number that is greater than or
equal to
2.0 and strictly less than 2.5 will return 2. (Since the function declaration for round
specifies that the type for the value returned is
int, we have type cast the computed value to the

type
int.)
Now consider numbers greater than or equal to
2.5; for example, 2.6. The value returned by the
call
round(2.6) is the following (converted to an int value):
floor(2.6 + 0.5)
which is floor(3.1), or 3.0. In fact, for any number that is greater than 2.5 and less than or
equal to
3.0, that number plus 0.5 will be greater than 3.0. Thus, round called with any num-
ber that is greater than
2.5 and less than or equal to 3.0 will return 3.
Thus,
round works correctly for all arguments between 2.0 and 3.0. Clearly, there is nothing
special about arguments between
2.0 and 3.0. A similar argument applies to all nonnegative
numbers. So,
round works correctly for all nonnegative arguments.
round
Display 3.6 The Function round
(part 1 of 2)
1 #include <iostream>
2 #include <cmath>
3 using namespace std;
4 int round(double number);
5 //Assumes number >= 0.
6 //Returns number rounded to the nearest integer.
7 int main( )
8 {
9 double doubleValue;

10 char ans;
11 do
12 {
13 cout << "Enter a double value: ";
14 cin >> doubleValue;
Testing program for
the function
round
Programmer-Defined Functions 109
Self-Test Exercises
7. What is the output produced by the following program?
#include <iostream>
using namespace std;
char mystery(int firstParameter, int secondParameter);
int main( )
{
cout << mystery(10, 9) << "ow\n";
return 0;
}
char mystery(int firstParameter, int secondParameter)
{
if (firstParameter >= secondParameter)
return ’W’;
else
return ’H’;
}
Display 3.6 The Function round
(part 2 of 2)
15 cout << "Rounded that number is " << round(doubleValue) << endl;
16 cout << "Again? (y/n): ";

17 cin >> ans;
18 }while (ans == ’y’ || ans == ’Y’);
19 cout << "End of testing.\n";
20 return 0;
21 }
22 //Uses cmath:
23 int round(double number)
24 {
25 return static_cast<int>(floor(number + 0.5));
26 }
S
AMPLE
D
IALOGUE
Enter a double value: 9.6
Rounded, that number is 10
Again? (y/n): y
Enter a double value: 2.49
Rounded, that number is 2
Again? (y/n): n
End of testing.
110 Function Basics
Self-Test Exercises
8. Write a function declaration (function prototype) and a function definition for a function
that takes three arguments, all of type
int, and that returns the sum of its three arguments.
9. Write a function declaration and a function definition for a function that takes one argu-
ment of type
double. The function returns the character value ’P’ if its argument is posi-
tive and returns

’N’ if its argument is zero or negative.
10. Can a function definition appear inside the body of another function definition?
11. List the similarities and differences between how you invoke (call) a predefined (that is,
library) function and a user-defined function.

FUNCTIONS THAT RETURN A BOOLEAN VALUE
The returned type for a function can be the type bool. A call to such a function returns
one of the values
true or false and can be used anywhere that a Boolean expression is
allowed. For example, it can be used in a Boolean expression to control an
if-else
statement or to control a loop statement. This can often make a program easier to read.
By means of a function declaration, you can associate a complex Boolean expression
with a meaningful name. For example, the statement
if (((rate >= 10) && (rate < 20)) || (rate == 0))
{

}
can be made to read
if (appropriate(rate))
{

}
provided that the following function has been defined:
bool appropriate(int rate)
{
return (((rate >= 10) && (rate < 20)) || (rate == 0));
}
12. Write a function definition for a function called inOrder that takes three arguments of
type

int. The function returns true if the three arguments are in ascending order; other-
wise, it returns
false. For example, inOrder(1, 2, 3) and inOrder(1, 2, 2) both
return
true, whereas inOrder(1, 3, 2) returns false.
Programmer-Defined Functions 111
13. Write a function definition for a function called even that takes one argument of type int
and returns a
bool value. The function returns true if its one argument is an even num-
ber; otherwise, it returns
false.
14. Write a function definition for a function
isDigit that takes one argument of type char
and returns a
bool value. The function returns true if the argument is a decimal digit; oth-
erwise, it returns
false.

DEFINING
void
FUNCTIONS
In C++ a void function is defined in a way similar to that of functions that return a
value. For example, the following is a
void function that outputs the result of a calcula-
tion that converts a temperature expressed in degrees Fahrenheit to a temperature
expressed in degrees Celsius. The actual calculation would be done elsewhere in the
program. This
void function implements only the subtask for outputting the results of
the calculation.
void showResults(double fDegrees, double cDegrees)

{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
cout << fDegrees
<< " degrees Fahrenheit is equivalent to\n"
<< cDegrees << " degrees Celsius.\n";
}
As the above function definition illustrates, there are only two differences between
a function definition for a
void function and for a function that returns a value. One
difference is that we use the keyword
void where we would normally specify the type
of the value to be returned. This tells the compiler that this function will not return
any value. The name
void is used as a way of saying “no value is returned by this func-
tion.” The second difference is that a
void function definition does not require a
return statement. The function execution ends when the last statement in the func-
tion body is executed.
A
void function call is an executable statement. For example, the above function
showResults might be called as follows:
showResults(32.5, 0.3);
If the above statement were executed in a program, it would cause the following to
appear on the screen:
32.5 degrees Fahrenheit is equivalent to
0.3 degrees Celsius.
void
function

definition
void
function
call

×