6.3. Math Library Functions
As you know, a class can provide member functions that perform the services of the class. For example, in Chapters 35, you have called the member functions of various versions of a GradeBook object to display the GradeBook's welcome message, to set its course name, to obtain a set of grades and to calculate the average of those grades.
Sometimes functions are not members of a class. Such functions are called global functions. Like a class's member functions, the function prototypes for global functions are placed in header files, so that the global functions can be reused in any program that includes the header file and that can link to the function's object code. For example, recall that we used function pow of the <cmath> header file to raise a value to a power in Figure 5.6. We introduce various functions from the <cmath> header file here to present the concept of global functions that do not belong to a particular class. In this chapter and in subsequent chapters, we use a combination of global functions (such as main) and classes with member functions to implement our example programs.
The <cmath> header file provides a collection of functions that enable you to perform common mathematical calculations. For example, you can calculate the square root of 900.0 with the function call
sqrt( 900.0 )
The preceding expression evaluates to 30.0. Function sqrt takes an argument of type double and returns a double result. Note that there is no need to create any objects before calling function sqrt. Also note that all functions in the <cmath> header file are global functionstherefore, each is called simply by specifying the name of the function followed by parentheses containing the function's arguments.
Function arguments may be constants, variables or more complex expressions. If c = 13.0, d = 3.0 and f = 4.0, then the statement
cout << sqrt( c + d * f ) << endl;
calculates and prints the square root of 13.0 + 3.0 * 4.0 = 25.0namely, 5.0. Some math library functions are summarized in Fig. 6.2. In the figure, the variables x and y are of type double.