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 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 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. |
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