← Back to C Course | Chapter 12: Advanced Topics | Lesson 11 of 20

C math.h Functions

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

c
#include <stdio.h>
#include <math.h>
int main() {
	double radians = 0;
	printf("%.1f", cos(radians));
	return 0;
}

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

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.2f %.2f", log(2.718281828), log10(100.0));
	return 0;
}

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

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.2f", exp(1.0));
	return 0;
}

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()

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.0f %.0f", round(2.5), round(-2.5));
	return 0;
}

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

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.1f %.1f", pow(2, 3), sqrt(16.0));
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.