In this C++ tutorial, you will learn how to compute square root of given number using sqrt() function of cmath, with syntax and examples.

C++ sqrt()

C++ sqrt() computes square root of given number (argument).

Syntax

The syntax of C++ sqrt() is

sqrt(x)

where

ParameterDescription
xA double, float, long double, or any integral type value.

Returns

The return value depends on the type of value passed for parameter x.

The return value of sqrt(x) is

  • double if x is double or integral type.
  • float if x is float.
  • long double if x is long double.

If x is negative, then sqrt() returns nan.

The synopsis of sqrt() function is

double sqrt(double x);
float sqrt(float x);
long double sqrt(long double x);
double sqrt(T x); // for integral type argument values

sqrt() is a function of cmath library. Include cmath library at the start of program, if using sqrt() function.

ADVERTISEMENT

Example

In this example, we read a value from user into variable x, and find its square root using sqrt() function.

C++ Program

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x;
    cout << "Enter a number : ";
    cin >> x;
    
    double result = sqrt(x);
    cout << "sqrt(" << x << ") : " << result << endl;
}

Output

Enter a number : 9
sqrt(9) : 3
Program ended with exit code: 0
Enter a number : 2
sqrt(2) : 1.41421
Program ended with exit code: 0
Enter a number : -2
sqrt(-2) : nan
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ sqrt(), and how to use this function to find the square root of given number, with the help of examples.