Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function – sqrt()

C Library Function - sqrt()

C Standard Library - <math.h> C Standard Library -

Description

C Library Function double sqrt(double x) Return x the square root of .

sqrt() is a function in the C standard library a function in used to calculate the square root of a non-negative number. This function is often used in mathematics and engineering.

Declaration

Below is the declaration of the sqrt() function.



#include 



double sqrt(double x);

float sqrtf(float x);

long double sqrtl(long double x);

Parameters

Return Value

Error handling

Example

The following example demonstrates the use of the sqrt() function.

Example

#include

#include

int

main

(

)

{

   

printf

(

"The square root of %lf is %lf\n"

,

4.0

,

sqrt

(

4.0

)

)

;

   

printf

(

"The square root of %lf is %lf\n"

,

5.0

,

sqrt

(

5.0

)

)

;

   

   

return

(

0

)

;

}

Let's compile and run the above program, which will produce the following result:



4.000000 的平方根是 2.000000

5.000000 的平方根是 2.236068

Handling the square root of multiple values

The following example shows how to handle square root calculations for multiple values:

Example

#include

#include

#include

int

main

(

)

{

   

double

values

[

]

=

{

16.0

,

25.0

,

100.0

,

1.0

,

0.0

}

;

   

int

num_values

=

sizeof

(

values

)

/

sizeof

(

values

[

0

]

)

;

   

for

(

int

i

=

0

;

i

<

num_values

;

i

++

)

{

       

double

x

=

values

[

i

]

;

        errno

=

0

;

 

// Reset errno

       

double

result

=

sqrt

(

x

)

;

       

if

(

errno

==

EDOM

)

{

           

printf

(

"Domain error: sqrt(%f) is not defined\n"

,

x

)

;

       

}

else

{

           

printf

(

"sqrt(%f) = %f\n"

,

x

,

result

)

;

       

}

   

}

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:

sqrt(16.000000) = 4.000000

sqrt(25.000000) = 5.000000

sqrt(100.000000) = 10.000000

sqrt(-1.000000) = nan

sqrt(0.000000) = 0.000000

Code Analysis

Use Cases

sqrt() The function has a wide range of uses in many applications, including but not limited to:

Summary

sqrt() The function is used to calculate the square root of a non-negative number and is an important tool for handling mathematical calculations. By properly using sqrt(), you can implement square root calculations in scientific computing, engineering applications, and mathematical problems, and ensure possible error conditions are handled properly.

C Standard Library - <math.h> C Standard Library -