🎓 A1Learner
🔍
0 of 50 lessons completed

C Math Functions

Math functions do ready-made maths for a program. They live in math.h, so a program includes that file first.

Square root

The square root of 25 is 5. The output prints it with six digits after the point.

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

int main() {
  printf("%f\n", sqrt(25.0));
  return 0;
}

A power

3 to the power of 4 is 81. The output prints it as a double.

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

int main() {
  printf("%f\n", pow(3.0, 4.0));
  return 0;
}

Round up and down

ceil rounds 7.2 up to 8, and floor rounds 7.8 down to 7. The output prints both as doubles.

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

int main() {
  printf("%f %f\n", ceil(7.2), floor(7.8));
  return 0;
}

Example

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

int main() {
  double first = 7.5;
  double second = 10.0;
  printf("Difference: %f\n", fabs(first - second));
  printf("Hypotenuse: %f\n", sqrt(pow(3.0, 2.0) + pow(4.0, 2.0)));
  printf("2 to the power of 10: %f\n", pow(2.0, 10.0));
  return 0;
}

Key points

  • math.h is a header file that holds maths tools.
  • The line #include <math.h> comes before main when a program uses a maths function.
  • sqrt works out the square root of a number.
  • sqrt(25.0) gives 5.0.
  • pow raises one number to the power of another number.
  • pow(3.0, 4.0) gives 81.0.
  • ceil pushes a number up to the next whole number.
  • floor pulls a number down to the next whole number.
  • fabs drops the sign of a number and gives its size.

fabs gives the size of the gap between 7.5 and 10.0, which is 2.5. Then pow squares 3.0 and 4.0, and sqrt takes the square root of their sum, which is 5.0. The last line shows 2 to the power of 10, which is 1024.0.

Note

sqrt with a variable needs -lm at the end of the gcc command, as in gcc main.c -o main -lm.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which header file gives a program sqrt and pow?