Quiz 1 - Apple Pricing

Overview

This quiz tests your understanding of variables, functions, and if expressions.


The Problem

Mary is buying apples with these rules:

  • Each apple costs 2 rustbucks
  • If she buys more than 40, each apple costs only 1 rustbuck

Solution

fn calculate_price_of_apples(n_apples: u64) -> u64 {
    if n_apples > 40 {
        n_apples       // 1 rustbuck each
    } else {
        2 * n_apples   // 2 rustbucks each
    }
}

Concepts Demonstrated

ConceptExample in Solution
Function with parameterfn calculate_price_of_apples(n_apples: u64)
Return type annotation-> u64
If expressionif n_apples > 40 { ... } else { ... }
Implicit returnNo semicolons on return expressions

Test Cases

assert_eq!(calculate_price_of_apples(35), 70);   // 35 * 2 = 70
assert_eq!(calculate_price_of_apples(40), 80);   // 40 * 2 = 80
assert_eq!(calculate_price_of_apples(41), 41);   // 41 * 1 = 41
assert_eq!(calculate_price_of_apples(65), 65);   // 65 * 1 = 65

Note: The discount applies at more than 40, not at exactly 40!