One way to find the average of all elements in an array in Rust is to loop through the array and calculate the sum of all elements. Then divide the sum by the length of the array to get the average. Here's the code:
main.rs219 chars13 lines
In this example, we have an array of integers with five elements. We initialize a variable sum
to zero and then loop through the array using a standard for loop. Inside the loop, we add the current element to the sum
variable.
After the loop, we calculate the average by dividing the sum
by the length of the array. We use as f32
to convert the sum and length to floating-point numbers because otherwise the division would result in integer division, which would discard the fractional part.
Finally, we print the result using println!()
.
gistlibby LogSnag