<math.h> LibraryThe <math.h> header file in C provides a wide range of powerful mathematical functions to perform complex calculations. Whether you need to calculate square roots, exponentiation, logarithms, or trigonometric values, the math library has built-in solutions.
By default, most functions in <math.h> accept and return values of type double for high-precision calculations.
Crucial Compilation Step: On many Unix/Linux systems (using GCC), the math library is not linked by default. You must append the -lm flag when compiling your program: gcc main.c -o program -lm
sqrt(double x): Calculates the square root of x.pow(double base, double exp): Calculates base raised to the power of exp.#include <stdio.h> #include <math.h>int main() { double num = 16.0; printf("Square root of 16 is: %f\n", sqrt(num)); printf("2 to the power of 3 is: %f\n", pow(2.0, 3.0)); return 0; }
If you have a floating-point number and need to convert it to a whole number representation, <math.h> provides several rounding options:
ceil(double x): Rounds the number up to the nearest integer.floor(double x): Rounds the number down to the nearest integer.round(double x): Rounds to the mathematically nearest integer (e.g., 2.5 becomes 3.0).#include <stdio.h> #include <math.h>int main() { double val = 4.3; printf("Original: %f\n", val); printf("Ceil (Up): %f\n", ceil(val)); // Output: 5.000000 printf("Floor (Down): %f\n", floor(val)); // Output: 4.000000 printf("Round: %f\n", round(val)); // Output: 4.000000 return 0; }
To get the positive version of a number (distance from zero), use absolute value functions:
fabs(double x): Returns the absolute value of a floating-point number (part of <math.h>).abs(int x): Returns the absolute value of an integer (Note: This function is actually located in <stdlib.h>).C provides standard trigonometric functions like sin(), cos(), and tan().
Important: These functions expect their arguments to be provided in radians, not degrees!
#include <stdio.h> #include <math.h>#define PI 3.14159265
int main() { double degrees = 90.0; double radians = degrees * (PI / 180.0); // Convert degrees to radians printf("The sine of 90 degrees is: %f\n", sin(radians)); // Output: ~1.000000 return 0; }
Which compiler flag is often required on Linux/Unix systems to link the math library?