Labs ICT
Pro Login

Math

C++ has a powerful mathematics library called cmath that gives you all the mathematical functions you could need. Square roots, powers, absolute values, trigonometric functions — it is all there.

Using cmath

To use these functions, include <cmath>. Here are some of the most commonly used ones:

  • sqrt(x) — square root of x
  • pow(x, y) — x raised to the power of y
  • abs(x) — absolute value of x
  • round(x) — rounds x to nearest integer
  • ceil(x) — rounds x up
  • floor(x) — rounds x down
#include <iostream>
#include <cmath>
using namespace std;

int main() {
  double num = 25.0;

  cout << "sqrt(25) = " << sqrt(num) << endl;
  cout << "pow(5, 3) = " << pow(5, 3) << endl;
  cout << "abs(-10) = " << abs(-10) << endl;
  cout << "round(4.7) = " << round(4.7) << endl;
  cout << "ceil(4.2) = " << ceil(4.2) << endl;
  cout << "floor(4.9) = " << floor(4.9);
  return 0;
}

These functions all return double values. If you pass an integer, C++ will convert it automatically. The cmath library is one of those things you will find yourself using in almost every program that involves calculations.