Lesson 57 +10 XP

C++ Math Functions

C++ Math Functions

C++ has a box of ready-made math tools. Open it with the header <cmath>, then call the function that fits the job.

The header

#include <cmath>
using namespace std;

Basic: max and min

max(x, y) returns the bigger one, min(x, y) the smaller:

cout << max(5, 10) << endl;   // 10
cout << min(5, 10) << endl;   // 5

Roots and powers

sqrt(x) gives the square root, pow(base, exp) raises a base to a power:

cout << sqrt(64) << endl;     // 8
cout << pow(2, 5) << endl;    // 32

Rounding: round, ceil, floor

round(x) snaps to the nearest whole number, ceil always rounds up, floor always rounds down:

cout << round(2.6) << endl;   // 3
cout << ceil(2.1) << endl;    // 3
cout << floor(2.9) << endl;   // 2

Abs and log

abs(x) strips the sign, log(x) gives the natural logarithm:

cout << abs(-5) << endl;      // 5
cout << log(1) << endl;       // 0

TL;DR

  • Include <cmath> to unlock math functions.
  • max and min compare two values.
  • sqrt, pow, round, ceil, floor, abs, log cover most needs.
  • Rounding: round nearest, ceil up, floor down.