Lesson 27 of 31

Math Functions

The <math.h> Library

C's standard math library provides a rich set of mathematical functions. Include it with:

#include <math.h>

Common Functions

FunctionDescriptionExample
sqrt(x)Square rootsqrt(9.0) → 3.0
pow(x, y)x raised to power ypow(2.0, 10.0) → 1024.0
fabs(x)Absolute value (float)fabs(-3.5) → 3.5
floor(x)Round downfloor(4.9) → 4.0
ceil(x)Round upceil(4.1) → 5.0
round(x)Round to nearestround(3.5) → 4.0

All math functions work on double (64-bit floating-point). Use %f or %.Nf to print them.

Printing Floats

Use %f for default 6 decimal places, or %.Nf for exactly N:

printf("%f\n", sqrt(2.0));    // 1.414214
printf("%.2f\n", sqrt(2.0));  // 1.41
printf("%.4f\n", sqrt(2.0));  // 1.4142

Integer vs Floating-Point Absolute Value

Note: abs() from <stdlib.h> is for integers. Use fabs() for doubles:

int a = abs(-5);       // 5  (integer)
double b = fabs(-5.0); // 5.0 (floating-point)

Your Task

Using <math.h>, compute and print with %.2f:

  1. sqrt(144.0)
  2. pow(2.0, 8.0)
  3. fabs(-3.14)
  4. floor(4.9)
  5. ceil(4.1)
  6. round(3.5)
TCC compiler loading...
Loading...
Click "Run" to execute your code.