Maths Functions
Learn how C++ uses the cmath library to perform functions like square root, power, and trigonometry.
We'll cover the following...
We'll cover the following...
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
.
Press + to interact
#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:
Press + to interact
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
To compute the power of a number, write ...