What is the sqrt() function in C++?
Overview
The sqrt() function in C++ is used to return the square root of a given number.
The sqrt() function is defined in the <cmath> header file.
Syntax
sqrt(double num);
Parameters
The sqrt() function takes a non-negative number as a parameter.
Note: The domain error occurs when a negative number is passed as an argument to the
sqrt()function.
Return value
The sqrt() function returns the square root of the argument passed to it.
Code
#include <iostream>#include <cmath>using namespace std;int main() {// creating a variabledouble x = 25;// using the sqrt() functiondouble result = sqrt(x);cout << "Square root of " << x << " is " << result;return 0;}
Explanation
- Line 7: We create a variable
x. - Line 10: We use the
sqrt()function to calculate the square root of variablexand assign the return value to the variableresult. - Line 12: We print the variable
result.