wleci
AboutProjectsBlogContact
Contact
Back to blog
C++MathTutorial

The <cmath> Library in C++ – Math Essentials

An overview of essential math functions in C++: from powers and roots to advanced trigonometry.

January 28, 20261 min read
Share:

Introduction to <cmath>

The <cmath> library (inherited from C as math.h) provides a set of functions for mathematical operations on floating-point numbers. All functions reside in the std namespace.

Basic Operations

The most commonly used functions include:

  • std::pow(base, exp) – Calculates power baseexpbase^{exp}baseexp.
  • std::sqrt(x) – Square root x\sqrt{x}x​.
  • std::abs(x) – Absolute value ∣x∣|x|∣x∣.

Rounding Functions

Choosing the right rounding function is crucial for calculation precision:

  • std::ceil(x): Rounds up (ceiling).
  • std::floor(x): Rounds down (floor).
  • std::round(x): Rounds to the nearest integer.
  • std::trunc(x): Truncates the fractional part (rounds towards zero).

Trigonometry

Remember that trigonometric functions in C++ expect arguments in radians, not degrees:

cpp
#include <iostream> #include <cmath> int main() { double degrees = 90.0; double radians = degrees * (M_PI / 180.0); std::cout << "Sin of 90 degrees: " << std::sin(radians) << std::endl; return 0; }

Note: The M_PI constant is not strictly part of the C++ standard, though many compilers provide it. In modern C++ (C++20 and later), it's better to use std::numbers::pi from the <numbers> header.

You might also like

C++Programming

Understanding the #include Directive in C++

A guide to the #include directive: learn how the preprocessor links files and why the choice of brackets matters.

1 min read
C++C

C-Style Strings: Char Arrays and Null Termination

Understanding low-level text handling: how character arrays terminated by a null byte work.

2 min read
C++Algorithms

Basic C++ Algorithms: Sorting, Searching, and Generating

Harness the power of the <algorithm> library. A guide to std::sort, std::find, std::copy, and sequence generation.

1 min read
Back to blog
wleci.pl

Full-stack Developer

I build modern web applications with passion for clean code and good design.

[email protected]
Poland

Navigation

  • Home
  • About
  • Projects
  • Blog
  • Contact

Services

  • Web applications
  • Websites
  • API & Backend
  • Consulting

Technologies

  • React / Next.js
  • TypeScript
  • Node.js
  • PostgreSQL

Social

© 2026 wleci.pl. All rights reserved.

Privacy policy•Terms of service

Made with in Poland