find the area of a regular polygon inscribed in a circle in rust

To find the area of a regular polygon inscribed in a circle, we can use the formula:

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

where A is the area of the polygon, n is the number of sides, s is the length of each side, and pi is the mathematical constant pi.

In rust, we can define a function to calculate the area of the polygon as follows:

main.rs
fn polygon_area(n: i32, r: f64) -> f64 {
    let s = 2.0 * r * (std::f64::consts::PI / n as f64).sin();
    (n as f64 * s.powi(2)) / (4.0 * (std::f64::consts::PI / n as f64).tan())
}
183 chars
5 lines

In this function, n is the number of sides of the polygon and r is the radius of the circle that the polygon is inscribed in.

We first calculate the length of each side s using the formula s = 2 * r * sin(pi/n). We then use the formula mentioned above to calculate the area of the polygon and return the result.

Here's an example usage of the function:

main.rs
fn main() {
    let n = 6;
    let r = 5.0;
    let area = polygon_area(n, r);
    println!("Area of an {}-sided polygon inscribed in a circle of radius {}: {}", n, r, area);
}
177 chars
7 lines

This outputs:

main.rs
Area of an 6-sided polygon inscribed in a circle of radius 5: 64.9519052838329
79 chars
2 lines

Note that we use the mathematical constant pi from the std::f64::consts module in Rust for these calculations.

gistlibby LogSnag