Rust Fundamentals · 15 XP Pro
Floats and casts
Rust has two floating-point types: f32 and f64. Prefer f64, which is the
default for literals like 2.5. Floats and integers never mix implicitly:
3 + 0.5 is a compile error. Convert explicitly with as:
let n: i32 = 7;
let half = n as f64 / 2.0; // 3.5
let whole = 3.99_f64 as i32; // 3
Rules worth remembering:
- Float to integer truncates toward zero:
-2.7 as i32is-2. Values out of range saturate at the integer's limits. - Integer to a narrower integer keeps only the low bits:
300 as u8is44. asbinds tighter than/, son as f64 / 2.0castsnfirst.
For rounding, floats have methods: .round(), .floor(), .ceil() and
.abs(). To round to two decimals, scale up, round, and scale back down:
let x = 3.14159_f64;
let r = (x * 100.0).round() / 100.0; // 3.14
Because floats are approximate, tests compare them with a small tolerance rather than exact equality.
Your task
Write these public functions:
average(a: i32, b: i32) -> f64: the exact mean, soaverage(1, 2)is1.5.truncate(x: f64) -> i32: drop the fractional part withas.round_to_cents(x: f64) -> f64: round to two decimal places.