sqrt() / pow() / fabs() / ceil() / floor()
Common math functions for square roots, exponentiation, absolute values, ceiling, and floor. They are defined in <math.h>, and you may need to pass the -lm linker option at compile time.
Syntax
double sqrt(double x); // Returns the positive square root of x (x >= 0 required). double pow(double x, double y); // Returns x raised to the power of y. double fabs(double x); // Returns the absolute value of a double. double ceil(double x); // Returns the smallest integer value >= x (ceiling). double floor(double x); // Returns the largest integer value <= x (floor). double round(double x); // Rounds to the nearest integer (C99 and later). double fmax(double x, double y);// Returns the larger of x and y (C99 and later). double fmin(double x, double y);// Returns the smaller of x and y (C99 and later).
Function List
| Function | Description | Example |
|---|---|---|
| sqrt() | Square root. | sqrt(9.0) → 3.0 |
| pow() | Exponentiation. | pow(2.0, 10.0) → 1024.0 |
| fabs() | Absolute value. | fabs(-3.5) → 3.5 |
| ceil() | Ceiling function (round up). | ceil(1.2) → 2.0 |
| floor() | Floor function (round down). | floor(1.9) → 1.0 |
| round() | Round to nearest integer. | round(1.5) → 2.0 |
| fmax() | Returns the larger value. | fmax(3.0, 5.0) → 5.0 |
| fmin() | Returns the smaller value. | fmin(3.0, 5.0) → 3.0 |
Sample Code
#include <stdio.h>
#include <math.h>
int main(void) {
// Compute a square root with sqrt.
printf("sqrt(2.0) = %.6f\n", sqrt(2.0)); // Outputs "1.414214".
// Compute an exponent with pow.
printf("2^10 = %.0f\n", pow(2.0, 10.0)); // Outputs "1024".
// Compute the absolute value of a floating-point number with fabs.
printf("fabs(-3.7) = %.1f\n", fabs(-3.7)); // Outputs "3.7".
// Round toward an integer with ceil and floor.
double val = 2.3;
printf("ceil(%.1f) = %.1f\n", val, ceil(val)); // Outputs "3.0".
printf("floor(%.1f) = %.1f\n", val, floor(val)); // Outputs "2.0".
double neg = -2.3;
printf("ceil(%.1f) = %.1f\n", neg, ceil(neg)); // Outputs "-2.0".
printf("floor(%.1f) = %.1f\n", neg, floor(neg)); // Outputs "-3.0".
// Example: computing Euclidean distance.
double dx = 3.0, dy = 4.0;
printf("distance = %.1f\n", sqrt(dx*dx + dy*dy)); // Outputs "distance = 5.0".
return 0;
}
Notes
Some environments (e.g., GCC on Linux) will produce a linker error if you omit the -lm flag from the compile command.
Passing a negative value to sqrt() returns NaN (Not a Number). Always verify that the argument is non-negative. Error conditions can be detected via errno or fpclassify().
For trigonometric functions, see sin() / cos() / tan(). For logarithms and exponentiation, see log() / exp().
If you find any errors or copyright issues, please contact us.