How to calculate the average of an array of double values in Rust

1 Answer

0 votes
fn sum(arr: &[f64]) -> f64 {
    arr.iter().fold(0.0, |acc, x| acc + x)
}

fn average(arr: &[f64]) -> f64 {
    sum(arr) / arr.len() as f64
}

fn main() {
    let arr = &[3.14, 8.0, 2.87, 5.982, 10.0];
    
    println!("{:?}", average(arr));
}




/*
run:
 
5.9984
 
*/

 



answered Oct 17, 2022 by avibootz

Related questions

2 answers 209 views
1 answer 161 views
2 answers 167 views
1 answer 172 views
1 answer 163 views
2 answers 156 views
...