find the average of a list of numbers in rust

To find the average of a list of numbers in Rust, you can create a function that takes in a list of f64 numbers as a parameter, then calculates the sum of the values in the list and divides it by the length of the list. Here's an example implementation:

main.rs
fn calculate_average(numbers: &[f64]) -> f64 {
    let sum: f64 = numbers.iter().sum();
    let count: f64 = numbers.len() as f64;
    return sum / count;
}

fn main() {
    let numbers = [1.0, 2.0, 3.0, 4.0, 5.0];
    let average = calculate_average(&numbers);
    println!("The average is: {}", average);
}
309 chars
12 lines

In this example, we first define a function called calculate_average that takes in a slice of f64 numbers. We use the iter() method to create an iterator over the numbers, allowing us to use the sum() method to calculate the sum of the numbers. We then get the length of the slice and cast it to a f64, and divide the sum by the count to get the average. Finally, we return the calculated average.

We then define a main() function that creates an array of numbers, calls the calculate_average() function, and prints the calculated average to the console.

gistlibby LogSnag