CodeBlanks Logo Icon CodeBlanks

Average calculator

Write and test a function that computes the average of a Vec.

Final task: average

You'll write a function that computes the average of a list of grades. The average of an empty list is undefined; return Option<f64> to express this honestly:

fn ortalama(notlar: &[f64]) -> Option<f64> {
    if notlar.is_empty() {
        return None;
    }
    let mut toplam = 0.0;
    for n in notlar {
        toplam += n;
    }
    Some(toplam / notlar.len() as f64)
}

notlar.len() is a usize; it's converted with as f64 to divide by an f64.

Short form with iterators

The same calculation shrinks to one line with iterator methods:

let toplam: f64 = notlar.iter().sum();
let en_yuksek = notlar.iter().cloned().fold(f64::MIN, f64::max);

When printing the average, the {:.1} format shows one decimal place. Handle the result with match and give a meaningful message for an empty list.

Practice Grade average

Write the ortalama function above. Handle the result for [72.5, 88.0, 91.5] and an empty slice with match: print Ortalama: 84.0 ({:.1}) or Not yok.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn ortalama(notlar: &[f64]) -> Option<f64> {
    if notlar.is_empty() {
        return None;
    }
    let mut toplam = 0.0;
    for n in notlar {
        toplam += n;
    }
    Some(toplam / notlar.len() as f64)
}

fn main() {
    let dolu = vec![72.5, 88.0, 91.5];
    let bos: Vec<f64> = Vec::new();
    for liste in [&dolu, &bos] {
        match ortalama(liste) {
            Some(o) => println!("Ortalama: {:.1}", o),
            None => println!("Not yok"),
        }
    }
}

Expected output

Ortalama: 84.0
Not yok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If <code>toplam / 0.0</code> were computed for an empty list, what would the result be?

  • 0.0
  • Compile error
  • NaN (0.0 / 0.0) Correct answer
  • Panic

Explanation: Floating-point division by zero doesn't panic; it produces NaN, which spreads silently. Option avoids this trap.

2 Convert the type

Question
Some(toplam / notlar.len() ____)
Answer
Some(toplam / notlar.len() as f64)

Explanation: A usize value is converted with as f64 to divide by an f64.

3 Input and average result

Term Meaning
[72.5, 88.0, 91.5] Some(84.0)
[] None
[10.0] Some(10.0)
[1.0, 2.0] Some(1.5)

All lessons in Beginner