0
0
Rustprogramming~20 mins

Floating point types in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Floating Point Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using f32?

Consider the following Rust code snippet. What will it print?

Rust
fn main() {
    let x: f32 = 0.1 + 0.2;
    println!("{:.8}", x);
}
A0.30000001
B0.3
C0.4
D0.2
Attempts:
2 left
๐Ÿ’ก Hint

Remember that floating point numbers can have precision errors.

๐Ÿง  Conceptual
intermediate
1:00remaining
Which floating point type has higher precision in Rust?

Between f32 and f64 in Rust, which one provides higher precision?

ABoth have the same precision
Bf64 has higher precision
Cf32 has higher precision
DPrecision depends on the CPU architecture
Attempts:
2 left
๐Ÿ’ก Hint

Think about the number of bits used to store each type.

๐Ÿ”ง Debug
advanced
2:00remaining
Why does this Rust code cause a compilation error?

Look at this Rust code snippet. Why does it fail to compile?

Rust
fn main() {
    let x: f32 = 1.0;
    let y: f64 = 2.0;
    let z = x + y;
    println!("{}", z);
}
Af32 and f64 cannot be declared in the same function
BVariables x and y must be mutable to add
CThe println! macro does not support floating point numbers
DCannot add f32 and f64 directly without casting
Attempts:
2 left
๐Ÿ’ก Hint

Check the types involved in the addition operation.

๐Ÿ“ Syntax
advanced
1:30remaining
Which Rust code correctly declares a 64-bit floating point variable?

Choose the correct Rust syntax to declare a variable pi as a 64-bit floating point number with value 3.1415.

Alet pi: float64 = 3.1415;
Blet pi = 3.1415f32;
Clet pi: f64 = 3.1415;
Dlet pi = f64(3.1415);
Attempts:
2 left
๐Ÿ’ก Hint

Look at the correct Rust type name for 64-bit floats.

๐Ÿš€ Application
expert
2:30remaining
What is the value of variable `result` after this Rust code runs?

Analyze the following Rust code and determine the value of result after execution.

Rust
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);
}
Atrue
Bfalse
CCompilation error
DRuntime panic
Attempts:
2 left
๐Ÿ’ก Hint

Consider floating point precision and how to compare floats safely.