find the area of a regular polygon in swift

Here's an example function in Swift that calculates the area of a regular polygon given the number of sides (n) and the length of one side (s):

main.swift
func areaOfRegularPolygon(n: Int, s: Double) -> Double {
    let numerator = Double(n) * pow(s, 2)
    let denominator = 4 * tan(Double.pi / Double(n))
    return numerator / denominator
}
189 chars
6 lines

This function uses the formula for the area of a regular polygon:

main.swift
area = (n * s^2) / (4 * tan(pi / n))
37 chars
2 lines

where n is the number of sides, s is the length of one side, and pi is the mathematical constant PI.

The function first calculates the numerator and denominator separately, and then divides the numerator by the denominator to get the final area.

Here's an example usage of the function:

main.swift
let n = 5  // pentagon
let s = 10.0  // side length is 10 units
let area = areaOfRegularPolygon(n: n, s: s)
print("The area of the regular polygon is \(area) square units.")
174 chars
5 lines

This would output:

main.swift
The area of the regular polygon is 237.76429123254518 square units.
68 chars
2 lines

gistlibby LogSnag