|
Function libraries provide predefined functions for you. As noted earlier, we will only make limited use of libraries. But you can use some libraries, and this page discusses a few of them. Feel free to use any function mentioned on this page.
You need to request a library module in order to use what it provides. Function sqrt is part of the <cmath> library. To use <cmath>, put lines
#include <cmath> using namespace std;somewhere near the beginning of your program. (Notice that there is no semicolon at the end of the #include line, but there is a semicolon at the end of the using line.)
If you include several libraries, write a #include line for each, then write using namespace std; once.
In addition to sqrt(x), the <cmath> library provides the following.
pow(x, y) is (approximately)
x y, 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) is the absolute value of int n. |
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. |
Library <cstdio> provides printf and other functions that perform input and output. We will see more on input and output beginning on the next page.
Library <cstdlib> provides random, among many others.
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
double y = 10.0; double z = sqrt(y + 6);allowed? If so, what is the value of z? Answer
|