When using the math library, we need to include the math header file as illustrated in Part 1-1 .
#include <math.h>This header file give us the prototypes for the functions in the math library. (We'll see how this is done in Part 2-7 .) These prototypes tell us that most of the functions in the math library take arguments of type
doubleand also return double precision floating point numbers. Among the prototypes in the file
math.hare the following math functions:
double sin(double x);- sine of x
double cos(double x);- cosine of x
double tan(double x);- tangent of x
double asin(double x);- arc sine of x
double acos(double x);- arc cosine of x
double atan(double x);- arc tangent of x
double exp(double x);- e to the x power
double log(double x);- natural logarithm of x
double log10(double x);- common logarithm of x
double pow(double x, double y);- x to the y power
double sqrt(double x);- square root of x
sin(1.57)will return a number about 1.0.
Even though the math functions are defined to use double precision numbers, C's type handling will do what you expect if you use single precision floating point numbers as arguments or assign the return values to single precision numbers. For example,
float x, y; y = sqrt(x);will work perfectly well. However, for reasons of performance and computational accuracy it is usually advisable to go ahead and declare such variables as double precision.
printf()as we do for single precision floats. Specifically,
double x; ... printf("%f", x);is the proper way to print out double precision floating point numbers. However, the same is not true of
scanf(). Here, we have a different format specifier for the double precision numbers. To read in such a number, we'd use code like:
double x; ... scanf("%lf", &x);Notice that the format specifier for reading doubles is
%lf. This specifier can also be used when printing doubles, but it is not necessary.
acos()) function. We can also find the other angle by applying this procedure to the ratio of the other side to the hypotenuse.