C++ Crash Course: a fast-Paced Introduction



Yüklə 7 Mb.
Pdf görüntüsü
səhifə52/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   48   49   50   51   52   53   54   55   ...   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

Example: A Step Function
For demonstration purposes, this section shows how to build a mathematical 
function called 
step_function
that returns 
-1
for all negative arguments, 
0
for 
a zero-valued argument, and 
1
for all positive arguments. Listing 1-6 shows 
how you might write the 
step_function
.
int step_function(int 
u
x) {
int result = 0; 
v
if (x < 0) {
result = -1; 
w
} else if (x > 0) {
result = 1; 
x
}
return result; 
y
}
Listing 1-6: A step function that returns 
-1
 for negative values
0
 for zero, and 
1
 for posi-
tive values
The 
step_function
takes a single argument 
x
u
. The 
result
variable is 
declared and initialized to 
0
v
. Next, the 
if
statement sets 
result
to 
-1
w
if 
x
is less than 
0
. If 
x
is greater than 
0
, the 
if
statement sets 
result
to 
1
x

Finally, 
result
is returned to the caller 
y
.


18
Chapter 1
Calling Functions
To call (or invoke) a function, you use the name of the desired function
parentheses, and a comma-separated list of the required parameters. The 
compiler reads files from top to bottom, so the function’s declaration must 
appear before its point of first use.
Consider the program in Listing 1-7, which uses the 
step_function
.
int step_function(int x) {
--
snip
--
}
int main() {
int value1 = step_function(100); // value1 is 1
int value2 = step_function(0); // value2 is 0
int value3 = step_function(-10); // value3 is -1
}
Listing 1-7: A program using the 
step_function
. (This program produces no output.)
Listing 1-7 calls 
step_function
three times with different arguments and 
assigns the results to the variables 
value1

value2
, and 
value3
.
Wouldn’t it be nice if you could print these values? Fortunately, you can 
use the 
printf
function to build output from different variables. The trick is 
to use 
printf
format specifiers.

Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   48   49   50   51   52   53   54   55   ...   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin