Swift Double - squareRoot() Function



The squareRoot() method of the Double structure is used to calculate the square root of the given value.

For example, suppose we have number = 8.0. Using the squareRoot() method, we find its square root, which is 2.8284271247461903.

Syntax

Following is the syntax of the squareRoot() function −

 func squareRoot() 

Parameter

This method does not take any parameters.

Return Value

This method returns the square root of the given value.

Example 1

Swift program to demonstrate how to use the squareRoot() method:

 import Foundation // Input numbers var number1 : Double = 8.0 var number2 : Double = 4.0 var number3 : Double = 17.0 // Finding square root using squareRoot() method var result1 = number1.squareRoot() var result2 = number2.squareRoot() var result3 = number3.squareRoot() // Display result print("Square root of \(number1):", result1) print("Square root of \(number2):", result2) print("Square root of \(number3):", result3) 

Output

 Square root of 8.0: 2.8284271247461903 Square root of 4.0: 2.0 Square root of 17.0: 4.123105625617661 

Example 2

Swift program to calculate the square root of given numbers:

 import Foundation // Finding square root using squareRoot() method var result1 = 14.squareRoot() var result2 = 12.2.squareRoot() var result3 = 56.8.squareRoot() // Display result print("Square root of 14:", result1) print("Square root of 12.2:", result2) print("Square root of 56.8:", result3) 

Output

 Square root of 14: 3.7416573867739413 Square root of 12.2: 3.492849839314596 Square root of 56.8: 7.536577472566709 

Example 3

Swift program to calculate the hypotenuse of a triangle using the squareRoot() method:

 import Foundation // Function to calculate the hypotenuse of a triangle func triHypotenuse(x: Double, y: Double) -> Double { return (x * x + y * y).squareRoot() } let result = triHypotenuse(x: 5, y: 7) print("Hypotenuse of the triangle is", result) 

Output

 Hypotenuse of the triangle is 8.602325267042627 
Advertisements