main()
was.
Here we will take a much more detailed tour through functions.
#include <stdio.h> #include <math.h> float pythag(float side_a, float side_b); float square(float x); main() { float adjacent, opposite, hypotenuse; printf("What lengths are the adjacent and opposite sides? "); scanf("%f%f", &adjacent, &opposite); hypotenuse = pythag(adjacent, opposite); printf("The length of the hypotenuse is %f\n", hypotenuse); } float pythag(float side_a, float side_b) { return sqrt(square(side_a) + square(side_b)); } float square(float x) { return x * x; }
Looking at the functions for
pythag()
and
square()
at the bottom
of the program, we see that they look a lot like the function
declarations for main that we've already seen, but with some
additional features.
(Ignore the
pythag
and
square
at the
beginning of the program for now.
We'll see what that's for in
Part 2-5.
)
In particular they specify
parameters
and
return types.
The function:
float square(float x) { return x * x; }
The floating point square of a floating point number, x, is given by x * x.The first
float
, as in
float square(...
,
specifies that the function
square will return a floating point number as its result.
The
float x
inside the parentheses specified that
square
will take one
argument
(or
parameter
)
which is a floating point number and it will be called
x
inside the function.
If the function takes more than one parameter, then we list them
separated by commas as in the definition of
pythag()
.