Newbie Question

What is wrong with this code - adding extra parens for clarity changes the result by making the division float

fn main() {
let n = 138;
let a = n * (n + 1)/2;
let b = n * ((n + 1)/2);
println!("a = {}, b = {}", a, b);
}

a = 9591, b = 9522

It's not related to floating point—Rust doesn't implicitly coerce integers to floats or return floats from integer arithmetic operations—just an illustration of the fact that (a * b) / c is not always equal to a * (b / c) for integers a, b, c, when / has its conventional meaning in C-like programming languages. An illustration with smaller numbers would be 2 * (1 / 2) == 2 * 0 == 0 versus (2 * 1) / 2 == 2 / 2 == 1. Operator precedence (think PEMDAS) means that a * b / c is interpreted the same as (a * b) / c.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.