C Library Function - sqrt()
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
x: a non-negative number whose square root is to be calculated.
Return Value
- Return
xthe square root of . - If both the
xis negative, NaN is returned anderrnoisEDOM.
Error handling
- If both the
xis negative,sqrt()the function returns NaN and setserrnoisEDOM.
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
- Define an array containing multiple floating-point numbers
values. - Use
for, and loop through each value, calling thesqrt(x)Perform the computation. - Reset
errnoto 0 and check for possible errors. - Prints the square root calculation result for each value, or an error message.
Use Cases
sqrt() The function has a wide range of uses in many applications, including but not limited to:
- Calculate distances in geometry.
- Calculate velocity, acceleration, etc. in physics.
- Solve mathematical problems related to square roots.
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 -