In C++, the sqrt() function is defined in the <cmath> header file and is used to calculate the square root of a non-negative number. It returns the positive square root of the given value as a double-type result.
The sqrt() function supports integer and floating-point values, which are automatically converted to double before computation.
If a negative number is supplied to sqrt(), the result will be undefined in traditional real-number computation and may result in a domain error, depending on the context used.
It has the following syntax.
Here, x is a non-negative number whose square root that we want to compute. The provided value must be a numeric type that is compatible with double. It should be a positive or zero value. Passing a negative number will result in a domain error since the square root of a negative number is not defined within the set of real numbers.
Here, we are going to discuss several examples to demonstrate the sqrt() Function.
This example demonstrates how the sqrt() function calculates the square root of zero, positive integers, decimal values, and negative numbers.
Output:
The square root of 0 is: 0 The square root of 8 is: 2.82843 The square root of 10 is: 3.16228 The square root of 0.25 is: 0.5 The square root of -25 is: -nan (undefined in real numbers)
Explanation
In this example, we have taken the sqrt() function from the library to compute and display the square roots of various values, including zero, positive integers, decimals, and negative numbers. It shows how the sqrt() function responds to different types of input.
This example demonstrates how the sqrt() function calculates the square root of a positive number.
Output:
The square root of 16 is 4
Explanation:
In this example, we calculate the square root of a given number using the sqrt() function from the <cmath> library. After that, we initialize the number to 16.0, which computes its square root, and then display the result using cout.
When we use the sqrt() function in C++, there are a few important cases that can cause errors if not handled correctly.
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India