Lesson 79 +10 XP

Math Functions

Math Functions

The <math.h> header provides ready-made math tools.

The basics

#include <math.h>

printf("%f\n", sqrt(16));     // 4.0
printf("%f\n", pow(2, 3));    // 8.0
printf("%d\n", abs(-5));      // 5 (from stdlib.h)

Rounding helpers

ceil(2.1)    // 3
floor(2.9)   // 2
round(2.5)   // 3

More tools

  • fabs(x) - absolute value of a float.
  • fmod(x, y) - float remainder.
  • log(x), exp(x) - logarithms and exponent.

Two headers

  • <math.h> for floats/doubles math.
  • <stdlib.h> for abs (int absolute value).

TL;DR

  • <math.h> has sqrt, pow, ceil, floor, round.
  • abs for ints lives in <stdlib.h>.
  • Math functions return doubles mostly.
  • Include the right header or you get errors.