First Steps in (C) Programming, conclusion - Mathematical Functions
(Page 6 of 9 )
The math.h header file includes declarations for a wide range of mathematical functions. To give you a feel for what’s available, you’ll take a look at those that are used most frequently. All the functions return a value of type double.
You have the set of functions shown in Table 2-7 available for numerical calculations of various kinds. These all require arguments to be of typedouble.
Table 2-7. Functions for Numerical Calculations
Function | Operation |
floor(x) | Returns the largest integer that isn’t greater than x as type double |
ceil(x) | Returns the smallest integer that isn’t less than x as type double |
fabs(x) | Returns the absolute value of x |
log(x) | Returns the natural logarithm (base e) of x |
log10(x) | Returns the logarithm to base 10 of x |
exp(x) | Returns the value of ex |
sqrt(x) | Returns the square root of x |
pow(x, y) | Returns the value of xy |
Here are some examples of using these functions:
double x = 2.25;
double less = 0.0;
double more = 0.0;
double root = 0.0;
less = floor(x); /* Result is 2.0 */
more = ceil(x); /* Result is 3.0 */
root = sqrt(x); /* Result is 1.5 */
You also have a range of trigonometric functions available, as shown in Table 2-8. Arguments and values returned are again of typedouble and angles are expressed in radians.
Table 2-8. Functions for Trigonometry
Function | Operation |
sin(x) | Sine of x expressed in radians |
cos(x) | Cosine of x |
tan(x) | Tangent of x |
If you’re into trigonometry, the use of these functions will be fairly self-evident. Here are some examples:
double angle = 45.0; /* Angle in degrees */ double pi = 3.14159265;
double sine = 0.0;
double cosine = 0.0;
sine = sin(pi*angle/180.0); /* Angle converted to radians */
cosine = sin(pi*angle/180.0); /* Angle converted to radians */
Because 180 degrees is the same angle as π radians, dividing an angle measured in degrees by 180 and multiplying by the value of π will produce the angle in radians, as required by these functions.
You also have the inverse trigonometric functions available:asin(),acos(), andatan(), as well as the hyperbolic functionssinh(),cosh(), andtanh(). Don’t forget, you must includemath.hinto your program if you wish to use any of these functions. If this stuff is not your bag, you can safely ignore this section.
Next: Designing a Program >>
More C++ Articles
More By Apress Publishing
|
This article is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530). Check it out at your favorite bookstore. Buy this book now.
|
|