Provides common math functions for floating-point arithmetic. Link with -lm flag: gcc prog.c -lm. All trig functions work in radians.
Include: #include <math.h> | Compile: gcc -Wall -o prog prog.c
| Name | Prototype / Value | Description |
|---|---|---|
| sqrt | double sqrt(double x) | Square root of x |
| pow | double pow(double base, double exp) | base raised to the power exp |
| fabs | double fabs(double x) | Absolute value of x (floating-point) |
| ceil | double ceil(double x) | Round up to nearest integer |
| floor | double floor(double x) | Round down to nearest integer |
| round | double round(double x) | Round to nearest integer |
| fmod | double fmod(double x, double y) | Floating-point remainder of x/y |
| sin | double sin(double x) | Sine of x (radians) |
| cos | double cos(double x) | Cosine of x (radians) |
| tan | double tan(double x) | Tangent of x (radians) |
| asin | double asin(double x) | Arc-sine; result in [-π/2, π/2] |
| acos | double acos(double x) | Arc-cosine; result in [0, π] |
| atan | double atan(double x) | Arc-tangent of x |
| atan2 | double atan2(double y, double x) | Arc-tangent of y/x using both signs |
| exp | double exp(double x) | e raised to the power x |
| log | double log(double x) | Natural logarithm of x |
| log10 | double log10(double x) | Base-10 logarithm of x |
| log2 | double log2(double x) | Base-2 logarithm of x |
| hypot | double hypot(double x, double y) | Hypotenuse sqrt(x²+y²) |
| cbrt | double cbrt(double x) | Cube root of x |
Copy, save as demo.c, and compile with the command shown at the bottom.
#include <stdio.h>
#include <math.h>
/* Link with: gcc -Wall -o math_demo math_demo.c -lm */
#define PI 3.14159265358979323846
int main(void) {
double x = 2.0;
printf("sqrt(%.1f) = %.6f\n", x, sqrt(x));
printf("pow(2,10) = %.0f\n", pow(2, 10));
printf("sin(PI/6) = %.6f\n", sin(PI / 6));
printf("cos(0) = %.6f\n", cos(0.0));
printf("log(e) = %.6f\n", log(exp(1.0)));
printf("floor(3.9) = %.1f\n", floor(3.9));
printf("ceil(3.1) = %.1f\n", ceil(3.1));
printf("hypot(3,4) = %.1f\n", hypot(3.0, 4.0));
return 0;
}