C math.h Functions
In this page:
Trigonometric Functions
sin() and cos() compute the sine and cosine of an angle, but they expect that angle expressed in radians rather than degrees, so converting degrees to radians (multiplying by pi/180) before calling them is a common source of subtle bugs for anyone used to working in degrees.
Example: Trigonometric Functions
#include <stdio.h>
#include <math.h>
int main() {
double radians = 0;
printf("%.1f", cos(radians));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Logarithmic Functions
log() computes the natural logarithm, using base e, while log10() computes the common logarithm, using base 10 — picking the wrong one silently gives a mathematically different (and usually wrong-looking) result, so it's worth double-checking which base your formula actually calls for.
Example: Logarithmic Functions
#include <stdio.h>
#include <math.h>
int main() {
printf("%.2f %.2f", log(2.718281828), log10(100.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Exponential Functions
exp() raises the mathematical constant e to the power of the given argument, effectively computing the inverse operation of log(). It shows up frequently in growth and decay formulas, such as exponential smoothing or compound interest calculations.
Example: Exponential Functions
#include <stdio.h>
#include <math.h>
int main() {
printf("%.2f", exp(1.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Rounding with round()
round() rounds a floating-point value to the nearest whole number, and specifically rounds a value that sits exactly halfway between two integers away from zero (so 2.5 becomes 3, and -2.5 becomes -3), which differs from some other rounding conventions you may have seen elsewhere.
Example: Rounding with round()
#include <stdio.h>
#include <math.h>
int main() {
printf("%.0f %.0f", round(2.5), round(-2.5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Power and Square Root
pow() raises a base value to an arbitrary exponent, handling cases like fractional or negative exponents that a plain loop of repeated multiplication can't easily express, while sqrt() computes a value's non-negative square root directly and is more efficient than calling pow(x, 0.5) for that specific case.
Example: Power and Square Root
#include <stdio.h>
#include <math.h>
int main() {
printf("%.1f %.1f", pow(2, 3), sqrt(16.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- C typedef
- C Type Casting
- C Bit Fields
- C Variable Length Arrays
- C Command Line Arguments
- C Function Pointers
- C Callback Functions
- C Multidimensional Pointer
- C string.h Functions
- C stdlib.h Functions
- C math.h Functions
- C time.h Functions
- C ctype.h Functions
- C errno.h
- C assert.h
- C Error Handling
- C Debugging Techniques
- C Code Style & Best Practices
- C Common Mistakes
- C Interview Questions