What is the sqrt() function in Swift?
The sqrt() function in Swift 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
Foundationin our code to use thesqrt()function. We can import it like this:import Foundation.
Syntax
sqrt(number)
Parameter
sqrt() requires a non-negative number as a parameter.
Return value
sqrt() returns the square root of the number sent as a parameter.
Example
The code below shows the sqrt() function in Swift.
import Swiftimport Foundation//Perfect square rootprint ("The value of sqrt(4.0) : ", sqrt(4.0));print ("The value of sqrt(0.0) : ",sqrt(0.0));print ("The value of sqrt(25.0) : ",sqrt(25.0));//Non-perfect square rootprint ("The value of sqrt(4.4) : ",sqrt(4.4));//Exceptional outputsprint ("The value of sqrt(-4.5) : ",sqrt(-4.5));
Explanation
- Line 2: We add the
Foundationheader required forsqrt()function.
- Lines 4 to 8: We calculate the square root value of perfect square numbers
4,0, and25usingsqrt().
- Line 11: We calculate the square root value of the non-perfect square number
4.4usingsqrt().
- Line 14: We calculate the square root value of exceptional numbers
< 0usingsqrt().