book : problem solving and program design
CHAPTER 3
Library Functions
Library Functions
·
Predefined Functions and Code Reuse
A primary goal
of software engineering is to write error-free code. Code reuse, reusing
program fragments that have already been written and tested whenever possible,
is one way to accomplish this goal. Stated more simply, “Why reinvent the
wheel?”
·
Top-Down Design with Functions
C promotes reuse
by providing many predefined functions that can be used to perform mathematical
computations. C’s standard math library defines a function named sqrt that
performs the square root computation. The function call in the assignment
statement
y = sqrt(x);
function call
function
name
argument
activates the
code for function sqrt , passing the argument x to the function. You activate a
function by writing a function call. After the function executes, the function
result is substituted for the function call. If x is 16.0 , the assignment
statement
above is
evaluated as follows:
1. x is 16.0 ,
so function sqrt computes the 116.0 or 4.0.
2. The function
result, 4.0 , is assigned to y .
A function can
be thought of as a “black box” that has passed one or more input values and
automatically returns a single output value. Figure 3.6 illustrates this for
the call to function sqrt . The value of x ( 16.0 ) is the function input, and
the function
result, or
output, is 116.0 (result is 4.0 ).
If w is 9.0 ,
the assignment statement
z = 5.7 +
sqrt(w);
is evaluated as
follows:
1. w is 9.0 ,
so function sqrt computes the square root of 9.0 , or 3.0 .
2. The values
5.7 and 3.0 are added together.
3. The sum, 8.7
, is stored in z .
0 komentar:
Posting Komentar