The C math.h library. How to use sqrt, sin, cos, pow and other math functions.
What are Elementary Functions?
C comes with a familiar set of math functions built in: square roots, trigonometric functions, exponentials, logarithms, and more. To use them you need #include<math.h>.
Usage: (1) put #include<math.h> at the top, (2) call functionName(arg), (3) the return value is basically double.
#include<stdio.h>
#include<math.h> // ← required!
int main(void){
double x = 2.0;
printf("sqrt(%.1f) = %f\n", x, sqrt(x));
return 0;
}
Compile note: On Linux/Mac, gcc may require the -lm option (to link the math library): gcc prog.c -lm. Visual Studio does not need it.
Main Math Functions
All of these are available via #include<math.h>. Arguments and return values are basically double.
Function
Purpose
Example
Result
sqrt(x)
Square root √x
sqrt(9.0)
3.0
pow(x, y)
Power xy
pow(2.0, 10.0)
1024.0
fabs(x)
Absolute value |x|
fabs(-3.7)
3.7
sin(x)
Sine (radians)
sin(3.14159/2)
1.0
cos(x)
Cosine (radians)
cos(0.0)
1.0
tan(x)
Tangent (radians)
tan(3.14159/4)
≈ 1.0
exp(x)
Exponential ex
exp(1.0)
≈ 2.71828
log(x)
Natural log ln(x)
log(2.71828)
≈ 1.0
log10(x)
Common log log10(x)
log10(1000.0)
3.0
ceil(x)
Round up
ceil(2.3)
3.0
floor(x)
Round down
floor(2.7)
2.0
sqrt — Square Root
The first function we introduce. sqrt(x) returns the square root of x (√x).
#include<stdio.h>
#include<math.h>
int main(void){
double a = 2.0;
printf("sqrt(%.1f) = %f\n", a, sqrt(a)); // -> sqrt(2.0) = 1.414214