w3resource

Rust Program: Calculate average of Float values

Rust Iterators and Iterator Adapters: Exercise-6 with Solution

Write a Rust program that iterates over a vector of floats and calculates the average value.

Sample Solution:

Rust Code:

fn main() {
    // Define a vector of float values
    let floats = vec![10.5, 20.5, 30.5, 40.5, 50.5, 60.5];
    
    // Print the original vector elements
    println!("Original vector elements: {:?}", floats);
    
    // Calculate the sum of the float values
    let sum: f64 = floats.iter().sum();
    
    // Get the count of elements in the vector
    let count = floats.len();

    // Check if the vector is not empty
    if count > 0 {
        // Calculate the average value
        let average = sum / count as f64;
        
        // Print the average value
        println!("Average value: {}", average);
    } else {
        // Print a message if the vector is empty
        println!("The vector is empty.");
    }
}

Output:

Original vector elements: [10.5, 20.5, 30.5, 40.5, 50.5, 60.5]
Average value: 35.5

Explanation:

In the exercise above,

  • Define a vector 'floats' containing a list of floating-point values.
  • Use the "sum()" method on the iterator of the vector to calculate the sum of all the elements. This returns a single value of type "f64".
  • Get the length of the vector using the "len()" method to determine the number of elements.
  • Calculate the average by dividing the sum by the number of elements, converted to f64.
  • Finally, we print the average value. If the vector is empty, we print a message indicating that.

Rust Code Editor:


Previous: Rust Program: Count True and False values.
Next: Rust Program: Iterate over Option i32 values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-6.php