Rust Program: Calculate average of Float values
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.
 
Go to:
PREV : Rust Program: Count True and False values.
NEXT : Rust Program: Iterate over Option i32 values.
Rust Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
