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

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

main.rs
surface area = (number of sides) * (side length) * (radius of sphere)
70 chars
2 lines

In Rust, we can use the std::f64::consts::PI constant to represent the value of pi. We can define a function that takes the number of sides, the side length, and the radius of the sphere as arguments, and returns the surface area of the polygon.

main.rs
use std::f64::consts::PI;

fn surface_area_of_polygon(sides: i32, side_length: f64, sphere_radius: f64) -> f64 {
    let perimeter = sides as f64 * side_length;
    let apothem = sphere_radius * (perimeter / (2.0 * PI * sphere_radius)) / 2.0;
    let area = perimeter * apothem / 2.0;
    area * sides as f64
}
311 chars
9 lines

Here, we first calculate the perimeter of the polygon by multiplying the number of sides by the length of each side. Then, we calculate the apothem, which is the distance from the center of the polygon to the midpoint of any side. We can use the formula apothem = r * (p / (2 * pi * r)) / 2, where r is the radius of the sphere and p is the perimeter of the polygon.

Finally, we calculate the area of each triangle formed by connecting the center of the sphere to two adjacent vertices of the polygon. The surface area of the polygon is the product of the area of each triangle and the number of sides.

We can test our function by calculating the surface area of a regular octagon (a polygon with 8 sides) with a sphere radius of 5 units and a side length of 3 units.

main.rs
fn main() {
    let sides = 8;
    let side_length = 3.0;
    let sphere_radius = 5.0;
    let surface_area = surface_area_of_polygon(sides, side_length, sphere_radius);
    println!("Surface area of regular octagon = {:.2}", surface_area);
}
243 chars
8 lines

This should output:

main.rs
Surface area of regular octagon = 438.51
41 chars
2 lines

gistlibby LogSnag