๐ŸŽ“ A1Learner
๐Ÿ”

C++ Math

Math functions are ready-made tools that work out number results. The cmath library holds the math functions of this lesson.

Square root

std::sqrt gives the square root of 25. The result is 5, because 5 times 5 is 25.

#include <iostream>
#include <cmath>

int main() {
  std::cout << std::sqrt(25) << "\n";
  return 0;
}

A power

std::pow raises 2 to the power 3. The result is 2 times 2 times 2, which is 8.

#include <iostream>
#include <cmath>

int main() {
  std::cout << std::pow(2, 3) << "\n";
  return 0;
}

Larger and smaller

std::max gives the larger of the two values. std::min gives the smaller of the two.

#include <iostream>
#include <cmath>

int main() {
  std::cout << std::max(4, 9) << "\n";
  std::cout << std::min(4, 9) << "\n";
  return 0;
}

Rounding

std::round gives the nearest whole number. The value 3.6 rounds to 4.

#include <iostream>
#include <cmath>

int main() {
  std::cout << std::round(3.6) << "\n";
  return 0;
}

Example

#include <iostream>
#include <cmath>

int main() {
  double a = 3;
  double b = 4;
  double c = std::sqrt(std::pow(a, 2) + std::pow(b, 2));
  std::cout << "Hypotenuse: " << c << "\n";
  return 0;
}

Key points

  • The #include <cmath> line brings in the math functions.
  • A square root is a value that gives a number when the value is multiplied by itself.
  • std::sqrt gives the square root of a number.
  • A power multiplies a number by itself a set number of times.
  • std::pow gives a number raised to a power.
  • std::max gives the larger of two values, and std::min gives the smaller.
  • std::round gives the nearest whole number to a decimal value.

In this example, the two short sides of a right triangle hold 3 and 4. std::pow squares each side, giving 9 and 16. std::sqrt gives the square root of the sum 25, so the hypotenuse prints as 5.

Note

The hypotenuse is the longest side of a right triangle.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

What does std::sqrt(36) give?