Ticket machine change
A bus ticket machine counts money in whole cents so it never has rounding trouble. It knows the fare and the amount the passenger inserted, both in cents, and the passenger always inserts at least the fare. Read the two amounts and print the change as euros and cents in the form E.CC: the whole euros, a dot, then exactly two digits of cents, so 305 cents is printed as 3.05 and 7 cents as 0.07.
Input
Two lines: the fare in cents, then the amount inserted in cents. Both are integers and the second is never smaller than the first.
Output
One line: the change as E.CC, with the cents part always two digits.
Example 1
Input
250 500
Output
2.50
500 - 250 = 250 cents, which is 2 euros and 50 cents.
Example 2
Input
999 1000
Output
0.01
1 cent of change: zero euros and a two-digit cents part, so the leading zero matters.
Constraints
- 1 <= fare <= inserted <= 100000
Hints
Hint 1 of 3
Integer division / on unsigned integers throws the fraction away, and % gives what was left over.
Hint 2 of 3
change / 100 is the number of whole euros and change % 100 the remaining cents.
Hint 3 of 3
The format specifier {:02} pads a number with zeros to two digits, so println!("{}.{:02}", euros, cents) prints 0.07 for 7 cents.
Solution
Show a reference solution and explanation
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
let fare: u32 = lines.next().unwrap().unwrap().trim().parse().unwrap();
let paid: u32 = lines.next().unwrap().unwrap().trim().parse().unwrap();
let change = paid - fare;
let euros = change / 100;
let cents = change % 100;
println!("{}.{:02}", euros, cents);
}
Why it works
Keeping money in integer cents avoids the floating-point surprise where 0.1 + 0.2 is not quite 0.3. With u32 values, / performs integer division and % the remainder, which splits 250 cleanly into 2 euros and 50 cents. The only formatting need is the leading zero on single-digit cents, and the {:02} specifier handles it: the 0 is the fill character and 2 the minimum width. Because the inserted amount is never smaller than the fare, paid - fare cannot go below zero; with unsigned integers that guarantee matters, because a result below zero panics in a debug build and wraps around in a release build.
Lesson for this exercise: Data Types in Rust