6.2. Math Library Functions

Sometimes functions, such as main, 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 headers, so that the global functions can be reused in any program that includes the header and that can link to the function’s object code. For example, recall that we used function pow of the <cmath> header to raise a value to a power in Fig. 5.6. We introduce various functions from the <cmath> header here to present the concept of global functions that do not belong to a particular class.

The <cmath> header 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. There’s no need to create any objects before calling function sqrt. Also, all functions in the <cmath> header are global functions—therefore, each is called simply by specifying the name of the function followed by parentheses containing the function’s arguments. If you call sqrt with a negative argument, the function sets a global variable named errno to the constant value EDOM. The variable errno and the constant EDOM are defined in the <cerrno> header. We’ll discuss global variables in Section 6.9.


Image Error-Prevention Tip 6.1

Do not call sqrt with a negative argument. For industrial-strength code, always check that the arguments you pass to math functions are valid.


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;

displays the square root of 13.0 + 3.0 * 4.0 = 25.0—namely, 5.0. Some math library functions are summarized in Fig. 6.1. In the figure, the variables x and y are of type double.

Image
Image

Fig. 6.1. Math library functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.0.97