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
| Function | Description | Example |
|---|---|---|
sqrt(x) | Square root | sqrt(9.0) → 3.0 |
pow(x, y) | x raised to power y | pow(2.0, 10.0) → 1024.0 |
fabs(x) | Absolute value (float) | fabs(-3.5) → 3.5 |
floor(x) | Round down | floor(4.9) → 4.0 |
ceil(x) | Round up | ceil(4.1) → 5.0 |
round(x) | Round to nearest | round(3.5) → 4.0 |
All math functions work on
double(64-bit floating-point). Use%for%.Nfto 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:
sqrt(144.0)pow(2.0, 8.0)fabs(-3.14)floor(4.9)ceil(4.1)round(3.5)
TCC compiler loading...
Loading...
Click "Run" to execute your code.