expression

Explicit half-even rounding for nonnegative integer ratios

Round a nonnegative rational number to the nearest integer with ties to even. Compare r with d-r instead of doubling the remainder; reject zero divisors. This is an illustrative policy, not a legal or accounting requirement. Expected stdout (not executed): Some(2) Some(4) Some(3) Common mistake: Applying this unsigned policy to negative amounts without defining sign handling.

Formal Syntax & Structure

rust syntaxrust
q = n / d; r = n % d

Working Example

Example Snippetrust
fn main() {    fn half_even(n:u64,d:u64)->Option<u64> {        if d == 0 { return None; }        let (q,r)=(n/d,n%d);        let up = r > d-r || (r == d-r && q%2 == 1);        q.checked_add(u64::from(up))    }    println!("{:?} {:?} {:?}", half_even(5,2), half_even(7,2), half_even(8,3));}
Rust Reference