3C. Function Libraries


Including libraries

Some functions are available to C++ programs as long as the program #includes them. To include the <cmath> library, write

  #include <cmath>
  using namespace std;
The #include line is a preprocessor directive. Notice that it does not end on a semicolon, since the preprocessor is line-oriented. The using line is ordinary C++, and it does end on a semicolon.

Only write

  using namespace std;
once. To include both the <cmath> and <algorithm> libraries, write
  #include <cmath>
  #include <algorithm>
  using namespace std;


The <cmath> library

The <cmath> library provides a few mathematical functions, including the following.

sqrt(x)

Approximately the square root of x.

pow(x, y)

Approximately xy, where x and y are real numbers.

But to compute x2, you are better off writing x*x. It is much faster than pow(x, 2). Similarly, sqrt(x) is much faster than pow(x, 0.5).


abs(n)

The absolute value of int n.

fabs(x)

The absolute value of real number x.


The <algorithm> library

The <algorithm> library provides the following useful functions.

max(u, v)

The larger of u and v. For example, max(3,7) = 7 and max(5,5) = 5. This works for any numeric type.

min(u, v)

The smaller of u and v. For example, min(3,7) = 3 and min(3,3) = 3. This works for any numeric type.


Exercises

  1. What is the value of expression sqrt(25.0) Answer

  2. What is the value of expression max(3,8) Answer

  3. What is the value of expression max(2,2) Answer

  4. Is expression 2*sqrt(49) allowed? If so, what is its result? Answer