wleci
AboutProjectsBlogContact
Contact
Back to blog
MathC++Libraries

Stage 8: Basic Math Functions from the <cmath> Library

A detailed summary of the most important mathematical operations in C++ - an essential for every programming exam.

February 11, 20262 min read
Share:

The <cmath> Library: Calculation Foundations

During exams, you'll often face tasks requiring distance calculations, powers, or rounding. Instead of writing custom functions, use the <cmath> library, which is optimized and precise.


1. Basic Operations: Powers and Roots

The most important functions are pow and sqrt. Note: both functions take and return the double type.

  • pow(a, b): Calculates aba^bab (a to the power of b).
  • sqrt(x): Calculates x\sqrt{x}x​ (square root).
cpp
#include <iostream> #include <cmath> int main() { double base = 5.0; double exp = 2.0; std::cout << "Result: " << pow(base, exp) << std::endl; // 25.0 return 0; }

2. Rounding and Absolute Value

C++ provides several ways to control fractional parts depending on your needs.

  • ceil(x): Rounds up (e.g., 3.1 -> 4.0).
  • floor(x): Rounds down (e.g., 3.9 -> 3.0).
  • round(x): Mathematical rounding (up from .5).
  • fabs(x): Returns the absolute value of a floating-point number.

3. Trigonometry (Radians vs Degrees)

The most common trap! Functions like sin(), cos(), and tan() expect arguments in radians.

Conversion formula: rad=degrees⋅π180rad = degrees \cdot \frac{\pi}{180}rad=degrees⋅180π​

cpp
const double PI = 3.1415926535; double rad = 30.0 * (PI / 180.0); double s = sin(rad); // approx 0.5

Exam Tips

  1. Always use .0: When writing pow(2, 2), you risk ambiguity. Use pow(2.0, 2.0) instead.
  2. Error Handling: Remember that sqrt of a negative number won't trigger a compiler error, but your program will return NaN (Not a Number).
  3. PI Constant: If M_PI is not defined, use acos(-1.0) to get a highly accurate value of Pi.

You might also like

AlgorithmsC++

Stage 7: Basic Algorithms in C++ - Manual Implementation

A guide to copying, searching, sorting, and sequence generation algorithms without using the <algorithm> library.

3 min read
ReferencesC++

Stage 5: References and References as Function Parameters

Understanding the reference mechanism in C++: how variable aliases work and why they are key to efficient argument passing.

3 min read
BasicsC++

Stage 1: Basic Data Types in C++ - A Comprehensive Guide

A detailed discussion of data types in C++, considering memory sizes and common exam mistakes.

2 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