sqrt(), sqrtl() and sqrtf() in C++

Library FunctAion in C++ – sqrt(), sqrtl() and sqrtf()

There are several ways to calculate the square root of a number in C++. The most common way is to use the sqrt() function from the cmath library, which is a part of the C++ standard library.  The cmath header file contains two other inbuilt functions sqrtl() and sqrtf() for calculating the square root of a number having arguments of type long double and float respectively.

sqrt(), sqrtl() and sqrtf() in C++

C++ Library Function cmath sqrt()

In C++, the sqrt() function is included in cmath header file.

The sqrt() function is used to compute the square root of a number. Square root of a number is a value, which on multiplication by itself, gives the original number.

Syntax

double sqrt(double x);

sqrt() function return a double data type as result or as a square root of a number.,

Example:

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

int main() {
   
  double x = 9.0;
  double y = sqrt(x);
  
  cout << "The square root of " << x << " is " << y << endl;
  
  return 0;
}

Output

The square root of 9 is 3

C++ Library Function cmath sqrtl()

In C++, the sqrtl() function is included in cmath header file.

The sqrtl() function is used to compute the square root of a long double value. This function has output with more precision.

Syntax

long double sqrtl(long double x);
sqrtl() function returns a long double data type as result or as a square root of a number.

Example:

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

int main() {
    
  long double x = 1345.0;
  long double y = sqrtl(x);
  
  cout << "The square root of " << x << " is " << y << endl;
  
  return 0;
}

Output

The square root of 1345 is 36.6742

C++ Library Function cmath sqrtf()

In C++, the sqrtf() function is included in cmath header file.

The sqrtf() function is used to compute the square root of a float value.

Syntax

float sqrtf(float x);
sqrtf() function returns a float data type as result or as a square root of a number.

Example:

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

int main() {
    
  float x = 15.67;
  float y = sqrtf(x);
  
  cout << "The square root of " << x << " is " << y << endl;
  
  return 0;
}

Output

The square root of 15.67 is 3.95854

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription