Consider the following Rust code snippet. What will it print?
fn main() {
let x: f32 = 0.1 + 0.2;
println!("{:.8}", x);
}Remember that floating point numbers can have precision errors.
Adding 0.1 and 0.2 in f32 does not exactly equal 0.3 due to floating point precision. The printed value is slightly off, like 0.30000001.
Between f32 and f64 in Rust, which one provides higher precision?
Think about the number of bits used to store each type.
f64 uses 64 bits and provides higher precision than f32, which uses 32 bits.
Look at this Rust code snippet. Why does it fail to compile?
fn main() {
let x: f32 = 1.0;
let y: f64 = 2.0;
let z = x + y;
println!("{}", z);
}Check the types involved in the addition operation.
Rust does not allow adding f32 and f64 directly. You must cast one type to the other before adding.
Choose the correct Rust syntax to declare a variable pi as a 64-bit floating point number with value 3.1415.
Look at the correct Rust type name for 64-bit floats.
In Rust, f64 is the correct type for 64-bit floating point numbers. The syntax let pi: f64 = 3.1415; is correct.
Analyze the following Rust code and determine the value of result after execution.
fn main() {
let a: f64 = 0.1;
let b: f64 = 0.2;
let c = a + b;
let result = (c - 0.3).abs() < 1e-15;
println!("{}", result);
}Consider floating point precision and how to compare floats safely.
The sum a + b is very close to 0.3 but not exactly equal. The code checks if the difference is less than a tiny number, so result is true.