C ยท Chapter 29 of 45

C Math Functions

The <math.h> header provides a library of mathematical functions like square root, power, absolute value, trigonometric functions and more, that go beyond basic arithmetic operators.

When compiling on Linux with GCC, you may need to link the math library explicitly using the -lm flag.

Syntax
#include <math.h>
sqrt(x); pow(x, y);

Common functions

sqrt() computes a square root, pow(base, exp) raises a number to a power, fabs() returns the absolute value of a double, and floor()/ceil() round down or up.

Linking the math library

On some systems, using math.h functions requires compiling with `gcc file.c -o file -lm` so the linker can find the math library's implementation.

Example 1 (c)
#include <stdio.h>
#include <math.h>

int main() {
  printf("%.2f\n", sqrt(16.0));
  return 0;
}
Output
4.00

sqrt(16.0) computes the square root of 16, which is 4.

Example 2 (c)
#include <stdio.h>
#include <math.h>

int main() {
  printf("%.1f\n", pow(2.0, 3.0));
  return 0;
}
Output
8.0

pow(2.0, 3.0) raises 2 to the power of 3, giving 8.

Key points

  • Include <math.h> to access sqrt, pow, fabs and more.
  • Math functions typically work with double values.
  • On Linux/GCC you may need to add -lm when compiling.
  • floor() rounds down and ceil() rounds up to the nearest integer.
๐Ÿ’ก Note: Forgetting -lm on some Linux systems causes a 'undefined reference to sqrt' linker error.

๐Ÿ“ Quick Quiz

1. Which header provides sqrt() and pow()?

2. What does pow(2.0, 3.0) return?

3. What flag is sometimes needed when linking math.h on Linux?