find the surface area of a regular polygon circumscribed around a cylinder in rust

To find the surface area of a regular polygon circumscribed around a cylinder, we can use the following formula:

Surface area = (Perimeter of the polygon) × (Height of the cylinder)

The perimeter of a regular polygon can be found by multiplying the length of one side by the number of sides. For example, the perimeter of a regular hexagon with side length s is:

P = 6s

To implement this formula in Rust, we can define a function that takes the number of sides n, the side length s, and the height of the cylinder h as input, and returns the surface area:

main.rs
fn surface_area(n: i32, s: f64, h: f64) -> f64 {
    let p = n as f64 * s;  // perimeter of the polygon
    let sa = p * h;         // surface area of the cylinder
    return sa;
}
181 chars
6 lines

This function first calculates the perimeter p by multiplying the number of sides n with the side length s. It then calculates the surface area of the cylinder by multiplying the perimeter with the height h. Finally, it returns the surface area.

We can use this function as follows:

main.rs
fn main() {
    let n = 6;             // number of sides
    let s = 1.0;           // side length
    let h = 2.0;           // height of the cylinder
    let sa = surface_area(n, s, h);
    println!("Surface area: {}", sa);
}
229 chars
8 lines

This code defines the values of n, s, and h, calls the surface_area function with these values, and prints the result.

Note that this formula assumes that the regular polygon is circumscribed around the cylinder, i.e., each vertex of the polygon touches the base of the cylinder. If the polygon is inscribed instead, i.e., the sides of the polygon touch the sides of the cylinder, the formula for the perimeter would be different.

gistlibby LogSnag