Search⌘ K
AI Features

Maths Functions

Explore how to perform arithmetic and trigonometric calculations using C++ math functions from the cmath library. Learn to compute square roots, powers, and apply trigonometry in programming tasks like calculating the hypotenuse of triangles using Pythagoras and sine formulas.

C++ math library

The C++ math library is actually inherited from the C standard library. It is easy to use and is accessed by including cmath.

C++
#include <cmath>

Now that we have the cmath library, let’s use some neat functionality.

Square root

To compute the square root of a number, write sqrt followed by the number whose square root you want to calculate inside round brackets. If you write this with the cout statement, the result will be displayed on the screen. This is shown in the playground given below:

C++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float myFloat = 7.4;
cout << "The square root of " << myFloat << " is: " << sqrt(myFloat) << endl;
return 0;
}

Powers

...