C <math.h>

C Math Functions: The <math.h> Library

The <math.h> header file in C provides a wide range of powerful mathematical functions to perform complex calculations. Whether you need to calculate square roots, exponentiation, logarithms, or trigonometric values, the math library has built-in solutions.

By default, most functions in <math.h> accept and return values of type double for high-precision calculations.

Crucial Compilation Step: On many Unix/Linux systems (using GCC), the math library is not linked by default. You must append the -lm flag when compiling your program:
gcc main.c -o program -lm


1. Exponents and Roots

Roots and Powers

#include <stdio.h>
#include <math.h>

int main() { double num = 16.0; printf("Square root of 16 is: %f\n", sqrt(num)); printf("2 to the power of 3 is: %f\n", pow(2.0, 3.0)); return 0; }


2. Rounding Functions

If you have a floating-point number and need to convert it to a whole number representation, <math.h> provides several rounding options:

Rounding Examples

#include <stdio.h>
#include <math.h>

int main() { double val = 4.3; printf("Original: %f\n", val); printf("Ceil (Up): %f\n", ceil(val)); // Output: 5.000000 printf("Floor (Down): %f\n", floor(val)); // Output: 4.000000 printf("Round: %f\n", round(val)); // Output: 4.000000 return 0; }


3. Absolute Values

To get the positive version of a number (distance from zero), use absolute value functions:


4. Trigonometric Functions

C provides standard trigonometric functions like sin(), cos(), and tan().

Important: These functions expect their arguments to be provided in radians, not degrees!

Trigonometry Example

#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main() { double degrees = 90.0; double radians = degrees * (PI / 180.0); // Convert degrees to radians printf("The sine of 90 degrees is: %f\n", sin(radians)); // Output: ~1.000000 return 0; }


Exercise

?

Which compiler flag is often required on Linux/Unix systems to link the math library?