how to write Pythagorean theorem in swift?

Asked on 08/22/2024

1 search

To write the Pythagorean theorem in Swift, you can use a simple function that calculates the hypotenuse of a right triangle given the lengths of the other two sides. Here's a basic example:

import Foundation

func calculateHypotenuse(a: Double, b: Double) -> Double {
    return sqrt(a * a + b * b)
}

let sideA = 3.0
let sideB = 4.0
let hypotenuse = calculateHypotenuse(a: sideA, b: sideB)
print("The hypotenuse is \(hypotenuse)")

This function uses the sqrt function from the Foundation framework to calculate the square root, which is necessary for computing the hypotenuse according to the Pythagorean theorem: ( c = \sqrt{a^2 + b^2} ).

If you're interested in learning more about Swift's features and design, you might find the session A Swift Tour: Explore Swift’s features and design helpful.

how to write Pythagorean theorem in swift? | Ask WWDC