Skip to main content Skip to navigation

3.0 Math functions

C comes with a range of libraries to perform routine tasks - these are known collectively as the Standard C library. to use functions from this library, you must declare the appropriate header file, and also link in the appropriate library at compile time. One library you should get familiar with is the math library. This library contains functions for a range of mathematical operations, such as trig functions, exponentials, powers, log functions.

Putting it into Practice:

Code up the program below to see how to invoke some standard maths functions.
#include<stdio.h>	
#include<math.h>	

int main()
{
  int angle_degree;
  double angle_radian, pi, value;

  /* obtain pi  (alternatively just use pi = M_PI, where M_PI is defined in math.h)  */
  pi = 4.0*atan(1.0);
  printf("Value of PI = %f \n\n", pi);

  angle_degree=30;	
			
  angle_radian = pi * angle_degree/180.0 ;
  value = sin(angle_radian);
  printf("sine of %d degrees is %f \n ", angle_degree, value);
  return 0;
}
Compile this code by typing the following (assuming the source is called sine.c):
gcc sine.c -lm -o sine 
Notice how you must now link in the standard maths library using the -l command on the compile line. The -lm command tells the compile to look for the library libm.*.so in the directory /lib/