Library late fee
A library gives borrowers two days of grace on a late return. From the third overdue day the fee is 20 cents per day counted from the end of the grace period, but the fee never exceeds 600 cents however late the book is. Read the number of days overdue and print No fee when the book is still within the grace period, otherwise Fee: <cents> cents with the amount owed.
Input
One line: the number of days overdue, an integer.
Output
One line: No fee, or Fee: <cents> cents.
Example 1
Input
3
Output
Fee: 20 cents
Day 3 is the first chargeable day: (3 - 2) * 20 = 20.
Example 2
Input
32
Output
Fee: 600 cents
(32 - 2) * 20 = 600, which is exactly the cap; any later return costs the same.
Example 3
Input
0
Output
No fee
Zero days overdue is inside the grace period.
Constraints
- 0 <= days <= 10000
Hints
Hint 1 of 3
Handle the grace period first: if days is 2 or less there is nothing to charge.
Hint 2 of 3
Otherwise the raw fee is (days - 2) * 20; the cap means you want the smaller of that and 600.
Hint 3 of 3
Integers have a .min() method: ((days - 2) * 20).min(600).
Solution
Show a reference solution and explanation
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let line = stdin.lock().lines().next().unwrap().unwrap();
let days: u32 = line.trim().parse().unwrap();
if days <= 2 {
println!("No fee");
} else {
let fee = ((days - 2) * 20).min(600);
println!("Fee: {} cents", fee);
}
}
Why it works
An if/else chooses between the two output shapes, and inside the charged branch .min(600) applies the cap without a second if. The order of the checks is not just a matter of style: subtracting 2 from a u32 is only safe once you know days is above 2, which is exactly what the else branch guarantees, so testing the grace period first is necessary with unsigned arithmetic. In Rust if is an expression, so the same logic could be written as let fee = if days <= 2 { 0 } else { ... }; followed by a single decision about what to print.
Lesson for this exercise: Control Flow in Rust: if, loop, while and for