The sqrt function in C computes the nonnegative square root of a given number (sqrt parameters). It is declared in math.h
and takes one argument in the form of double and returns the value of type double. You should remember that if the argument is less than zero, a domain error occurs.
Syntax of sqrt function in C:
You can also use the sqrtf() function to work specifically with float and sqrtl() to work with long double type. See the below syntax.
float sqrtf( float arg ); (1) (since C99) double sqrt( double arg ); (2) long double sqrtl( long double arg );(3) (since C99)
Parameters:
x
=> floating types (double)
Return value:
If no errors occur, sqrt functions return √x
.
C program to understand the working of sqrt function:
Consider the below code where I am passing different characters in the sqrt function. You can see the output of this function with entered input.
#include <math.h> #include <stdio.h> int main() { double data, squareRoot; printf("Enter a number: "); scanf("%lf", &data); // Compute square root of data squareRoot = sqrt(data); //print square root of data printf("Square root of %f = %f",data, squareRoot); return 0; }
Output:
Enter a number: 16
Square root of 16.000000 = 4.000000
Note:
A domain error occurs if and only if an input argument is outside the domain over which the mathematical function is defined. On a domain error, the function returns an implementation-defined value.
Error handling
Errors are reported as specified in math_errhandling. A domain error occurs if arg is less than zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
- If the argument is less than -0, FE_INVALID is raised and NaN is returned.
- If the argument is +∞ or ±0, it is returned, unmodified.
- If the argument is NaN, NaN is returned.
#include <stdio.h> #include <math.h> #include <errno.h> #include <fenv.h> #pragma STDC FENV_ACCESS ON int main(void) { errno = 0; feclearexcept(FE_ALL_EXCEPT); printf("sqrt(-1.0) = %f\n", sqrt(-1)); if(errno == EDOM) { perror("errno == EDOM"); } if(fetestexcept(FE_INVALID)) { puts("FE_INVALID was raised"); } return 0; }
Output:
sqrt(-1.0) = nan
errno == EDOM: Domain error
FE_INVALID was raised
Recommended Post:
- C program to find all roots of a quadratic equation using switch case.
- C program to find the roots of a quadratic equation.
- How to find whether a given number is prime number in C?
- Use of isxdigit in C programming.
- How to use ispunct function in C programming?
- tolower function in C.
- How to use the islower function in C?
- Use of iscntrl function in C.