find the surface area of a regular polygon inscribed in a cylinder in swift

To find the surface area of a regular polygon inscribed in a cylinder, we need to calculate the sum of the surface areas of each face of the polygon and the surface area of the curved section of the cylinder.

Here's the Swift code to find the surface area of a regular polygon inscribed in a cylinder:

main.swift
func surfaceAreaOfPolygonInCylinder(numSides: Int, radius: Double, height: Double) -> Double {
    let polygonAngle = Double.pi / Double(numSides)
    let sideLength = 2 * radius * sin(polygonAngle)
    let baseArea = Double(numSides) * pow(sideLength, 2) / (4 * tan(polygonAngle))
    let lateralArea = Double(numSides) * sideLength * height
    let curvedArea = 2 * Double.pi * radius * height
    
    let surfaceArea = baseArea + lateralArea + curvedArea
    
    return surfaceArea
}
489 chars
12 lines

To use this function, pass in the number of sides of the regular polygon, the radius of the cylinder, and the height of the cylinder. The function will return the surface area of the regular polygon inscribed in the cylinder.

For example, to find the surface area of a regular pentagon inscribed in a cylinder with a radius of 5 and a height of 10, the code would be:

main.swift
let numSides = 5
let radius = 5.0
let height = 10.0

let surfaceArea = surfaceAreaOfPolygonInCylinder(numSides: numSides, radius: radius, height: height)

print("Surface area of regular polygon inscribed in cylinder: \(surfaceArea)")
234 chars
8 lines

This would output:

main.swift
Surface area of regular polygon inscribed in cylinder: 321.52933385765616
74 chars
2 lines

Note that the surface area is in square units, as the units of the radius and height were not specified in the question.

gistlibby LogSnag