The sqrt()
function in D returns the square root of a non-negative number.
The figure below shows the mathematical representation of the sqrt()
function:
Note: We need to import
std.math
in our code to use thesqrt()
function. We can import it with the following:import std.math
sqrt(number)
// The number should be floating, double, or real.
sqrt()
requires a non-negative number as a parameter.
sqrt()
returns the square root of the number sent as a parameter.
Note:
- If
-0.0
,real.infinity
,real.nan
, or-real.nan
is sent as a parameter, the function returns the parameter as it is.- If
-real.infinity
ornumber < 0.0
is sent as a parameter, the function returns-nan
.
The code below shows the use of the sqrt()
function in D.
import core.stdc.stdio;import std.stdio;//Header required for the functionimport std.math;int main(){//Perfect square rootwriteln ("The value of sqrt(4.0) : ",sqrt(4.0));writeln ("The value of sqrt(0.0) : ",sqrt(0.0));writeln ("The value of sqrt(25.0) : ",sqrt(25.0));//Non-perfect square rootwriteln ("The value of sqrt(4.4) : ",sqrt(4.4));//Exceptional outputswriteln ("The value of sqrt(-0.0) : ",sqrt(-0.0));writeln ("The value of sqrt(real.infinity) : ",sqrt(real.infinity));writeln ("The value of sqrt(-real.infinity) : ",sqrt(-real.infinity));writeln ("The value of sqrt(real.nan) : ",sqrt(real.nan));writeln ("The value of sqrt(-real.nan) : ",sqrt(-real.nan));writeln ("The value of sqrt(-4.5) : ",sqrt(-4.5));return 0;}
Line 4: We add the std.math
header required for the sqrt()
function.
Lines 9 to 13: We calculate the square root value of the perfect square numbers 4
, 0
, and 25
using sqrt()
.
Line 16: We calculate the square root value of a non-perfect square number 4.4
using sqrt()
.
Lines 19 to 24: We calculate the square root value of exceptional numbers using sqrt()
.