Some functions are available to C++ programs as long as the program #includes them the libraries that contain them. For example, the <cmath> library contains the sqrt function, where sqrt(x) is the (approximate) square root of x. 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.
Another library that you can use is called <algorithm>, and it provides functions max(x, y) and min(x, y), among others. (See below for details.) To include both the <cmath> and <algorithm> libraries, write
#include <cmath> #include <algorithm> using namespace std;where you Only write
using namespace std;once.
In addition to sqrt(x), the <cmath> library provides the following.
pow(x, y)
pow(x, y) is (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)
abs(n) is the absolute value of int n. |
fabs(x)
fabs(x) is the absolute value of real number x (of type double). |
The <algorithm> library provides the following useful functions.
max(u, v) is 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) is the smaller of u and v. For example, min(3,7) = 3 and min(3,3) = 3. This works for any numeric type. |
What is the value of expression sqrt(25.0) Answer
What is the value of expression max(3,8) Answer
What is the value of expression max(2,2) Answer
Is expression 2*sqrt(49) allowed? If so, what is its result? Answer