rust-by-practice icon indicating copy to clipboard operation
rust-by-practice copied to clipboard

Problem set Numbers, Integer Problem 5. Vague questioning.

Open delta549 opened this issue 2 years ago • 0 comments

Problem set:

// Fix errors and panics to make it work
fn main() {
   let v1 = 251_u8 + 8;
   let v2 = i8::checked_add(251, 8).unwrap();
   println!("{},{}",v1,v2);
}

The vagueness of the question here may be a cause for concern for someone new to this concept. The fundamental issue is that:

the literal `251` does not fit into the type `i8` whose range is `-128..=127`

Resolving this error can be handled by either changing the arithmetic to fit within the bounds of a u8/i8. Or by increasing the type to an i16/u16. The question merely asks you to resolve this.

The solution given is:

fn main() {
    let v1 = 247_u8 + 8;
    let v2 = i8::checked_add(119, 8).unwrap();
    println!("{},{}",v1,v2);
 }

Here the solution is to reduce the unsigned integer u8:

  • From 251 to 247 = 255 (The maximum value of a u8)
  • The signed i8 from (251, 8) to (119, 8) = 127 (The maximum positive value of an i8)

I believe here there should be a specific mention within the comment: // Fix errors and panics to make it work

To change the values of the integers and not the integer types themselves. Something like:

// Fix errors and panics to make it work. 
// Do this by changing the values to the maximum allowed for an i8 and u8 respectively.

Or

// Fix errors and panics to make it work. Without changing the type!.

Hopefully this will give the learner the specific scope to answer the question and get the solution provided.

delta549 avatar Mar 04 '23 14:03 delta549