find the volume of a regular polygon inscribed in a cylinder in swift

To find the volume of a regular polygon inscribed in a cylinder, we can use the following formula:

V = h * A / 3

where V is the volume of the cylinder, h is its height, and A is the area of the base of the inscribed regular polygon.

To calculate A, we can use the following formula:

A = n * s^2 * cot(pi/n) / 4

where n is the number of sides of the regular polygon, s is the length of each side, and cot is the cotangent function.

Here's the Swift code to implement these formulas:

main.swift
func volumeOfInscribedPolygonInCylinder(n: Int, r: Double, h: Double) -> Double {
    let s = 2 * r * sin(Double.pi / Double(n))
    let A = Double(n) * pow(s, 2) * cot(Double.pi / Double(n)) / 4
    let V = h * A / 3
    return V
}

func cot(_ x: Double) -> Double {
    return 1 / tan(x)
}
292 chars
11 lines

You can call the volumeOfInscribedPolygonInCylinder function with the number of sides n, the radius of the cylinder r, and its height h to get the volume of the inscribed polygon in the cylinder.

gistlibby LogSnag