← Back to C++ Course | Chapter 5: Functions | Lesson 13 of 13

C++ Math Functions

The cmath Header

The <cmath> header gives C++ programs access to a full library of numeric functions -- square roots, powers, trigonometry, rounding -- that would be tedious and error-prone to hand-write. It's the C++-wrapped version of C's <math.h>, placed inside the std namespace so functions are called as std::sqrt(x) rather than the bare sqrt(x) C uses.

Example: The cmath Header

cpp
#include <iostream>
#include <cmath>

int main() {
	std::cout << std::sqrt(16.0) << std::endl; // one of many functions in <cmath>
	return 0;
}

Power and Root Functions

std::pow(base, exponent) raises a number to a power and std::sqrt(x) computes a square root, both operating on and returning double by default; std::cbrt(x) gives the cube root directly without needing pow(x, 1.0/3), which is both clearer and more numerically accurate.

Example: Power and Root Functions

cpp
#include <iostream>
#include <cmath>

int main() {
	std::cout << std::pow(2, 10) << std::endl;
	std::cout << std::sqrt(25.0) << std::endl;
	return 0;
}

Rounding Functions

std::floor(x) rounds down to the nearest whole number, std::ceil(x) rounds up, and std::round(x) rounds to the nearest whole number using standard half-away-from-zero rules -- picking the right one matters because floor/ceil/round can each give a different result for the same input like 2.5.

Example: Rounding Functions

cpp
#include <iostream>
#include <cmath>

int main() {
	std::cout << std::floor(4.7) << " " << std::ceil(4.2) << " " << std::round(4.5) << std::endl;
	return 0;
}

Absolute Value and Sign Handling

std::abs(x) (from <cstdlib> for ints or <cmath>/<cstdlib> overloads for floating types) strips the sign from a number, useful for distance calculations or when you only care about magnitude; be careful to use the right overload since mixing int and floating-point abs can silently truncate.

Example: Absolute Value and Sign Handling

cpp
#include <iostream>
#include <cstdlib>
#include <cmath>

int main() {
	std::cout << std::abs(-5) << std::endl;    // int version, from <cstdlib>
	std::cout << std::fabs(-3.14) << std::endl; // floating-point version
	return 0;
}

Trigonometric Functions

std::sin, std::cos, and std::tan all expect their argument in radians, not degrees, which is the single most common bug when porting math from a degrees-based context -- multiply degrees by M_PI / 180.0 (or std::numbers::pi in C++20) to convert before calling them.

Example: Trigonometric Functions

cpp
#include <iostream>
#include <cmath>

int main() {
	double radians = 0.0; // sin/cos/tan expect radians, not degrees
	std::cout << std::sin(radians) << " " << std::cos(radians) << std::endl;
	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.