直接上代码:
use std::collections::HashMap;
// 获取平均数
pub fn get_average_number(vec_numbers:&Vec<i64>) -> Option<f64> {
if vec_numbers.is_empty() {
return None;
}
let mut result: f64 = 0.0;
for i in vec_numbers.iter() {
result += *i as f64;
}
result = result/vec_numbers.len() as f64;
return Some(result);
}
// 获取中位数
pub fn get_median_number(vec_numbers:&mut Vec<i64>) -> Option<f64> {
vec_numbers.sort();
let len = vec_numbers.len();
println!("{:?}", vec_numbers);
match vec_numbers.len()%2 {
1 => Some(vec_numbers[len/2 as usize] as f64),
_ => Some((vec_numbers[len/2 as usize - 1] + vec_numbers[len/2 as usize]) as f64/2.0),
}
}
// 获取众数
pub fn get_mode_number(vec_numbers:&mut Vec<i64>) -> Option<i64> {
let mut map_numbers: HashMap<i64, i64> = HashMap::new();
for i in vec_numbers {
let count = map_numbers.entry(*i).or_insert(0);
*count += 1;
}
let mut result: i64 = 0;
let mut value: i64 = 0;
for (k, v) in &map_numbers {
if *v >= value {
value = *v;
result = *k;
}
else {
continue;
}
}
Some(result)
}
需要注意的是,获取中位数的入参为可变引用,调用后原Vec的顺序会被改变