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.rs309 chars12 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