Getting 'mismatched types' when compiling

I'm trying to make a function that finds med, avg, mode vs. But at compiling im getting the error 26 | fn avg(list: &[usize]) -> f32 { | --- expected f32because of return type ... 32 | return avg; | ^^^ expectedf32, found usize``'. The code:

fn b_sort(list: &mut[usize])
{
    for _ in 0..list.len() {
        for j in 0..(&list.len()-1) {
            if list[j] > list[j+1] {
                list.swap( j, j+1 );
            }
        }
    }
}

fn med(list: &[usize]) -> usize {
    let len = list.len();
    if len % 2 == 0 {
        let med1 = list[len/2];
        let med2 = list[len/2 - 1];
        let med = (med1 + med2) / 2;
        return med;
    }
    else {
        let med = list[(len - 1) / 2];
        return med;
    }
}

fn avg(list: &[usize]) -> f32 {
    let mut sum = 0;
    for i in list {
        sum += *i;
    }
    let avg = sum / list.len();
    return avg;
}

fn main()
{
    let mut list = [3,1,18,10,15];
    b_sort(&mut list);
    println!("Sorted: {:?}", list);
    println!("Med: {}", med(&list));
    println!("Avg: {:?}", avg(&list));
}

Sorry for poor english.

sum and list.len() are both usize so their ratio is a usize, too (and integer division truncates, so even if this compiled, you would get the wrong result). You first need to convert both of them to f32 to get a correct type (and value). You can probably just do sum as f32 / list.len() as f32 in this case, but be aware that floating-point numbers can't represent every integer exactly.

Thanks, it worked for me:

fn avg(list: &[usize]) -> f32 {
    let mut sum = 0;
    for i in list{
        sum += i;
    }
    let avg = sum as f32 / list.len() as f32;
    return avg as f32;
}

Note that you don't have to cast avg at the end, it's already an f32 because it is the ratio of two other f32s.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.