HOME HTML EDITOR C JAVA PHP

C math.h: Mathematical Functions in c

The <math.h> header file contains various methods for performing mathematical operations. Most of these functions work with floating-point numbers (double and float) and return a double value.

1. Compiling with Math Library

On many Linux systems, you must explicitly tell the compiler to link the math library by adding the -lm flag at the end of your command.

gcc main.c -o program -lm

2. Basic Power and Square Root

Standard C operators do not include a symbol for powers (like ^ in some languages). You must use these functions:

3. Rounding and Remainder

C provides multiple ways to round numbers depending on the direction you need.

Function Result (Input: 3.2) Description
ceil(x) 4.0 Rounds up to the nearest integer.
floor(x) 3.0 Rounds down to the nearest integer.
round(x) 3.0 Rounds to the nearest integer.
fmod(x, y) 0.2 (if y=3) Returns the floating-point remainder.

4. Trigonometric Functions

These functions expect angles to be in Radians, not degrees.

// Formula: Radians = Degrees * (PI / 180)
double angle = 90.0 * (M_PI / 180.0);
printf("Sine: %f", sin(angle)); // Outputs 1.0000

5. Logarithmic and Exponential

6. Error Handling: Domain and Range

When you pass invalid numbers to math functions (like sqrt(-1)), C returns a special value called NaN (Not a Number) or HUGE_VAL for infinity.

Pro Tip: Always use double instead of float when working with the math library to prevent precision errors, as all math.h functions are optimized for double precision by default!