rustlings
rustlings copied to clipboard
struct3 - Is this the right way to take care that the divison result is not truncated
Hello,
I wonder if this is the code that is the right way to solve this challenge expecially the calculate fees function
#[derive(Debug)]
struct Package {
sender_country: String,
recipient_country: String,
weight_in_grams: i32,
}
impl Package {
fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {
if weight_in_grams <= 0 {
panic!()
} else {
return Package {sender_country, recipient_country, weight_in_grams};
}
}
fn is_international(&self) -> bool {
&self.sender_country != &self.recipient_country
}
fn get_fees(&self, cents_per_kg: i32) -> i32 {
(&self.weight_in_grams * cents_per_kg + (1000 / 2) ) / 1000
}
}
all test are green but I wonder if I use the right way to take care that the outcome of weight in grams / 1000
is not truncated.
Edit 1 :
or is this one better : (&self.weight_in_grams * cents_per_kg).div_euclid(1000)
that's what I did:
fn get_fees(&self, cents_per_kg: i32) -> i32 {
(cents_per_kg as f32 * (self.weight_in_grams as f32 / 1_000.0)) as i32
}
I converted the numbers to float during the operation, and then converted the result to i32
because that's what the function returns.
Also, I think you don't need to add &
before self
(at least the compiler didn't throw any warning)
nice to see other ways to solve this
Yes, @benjaminfjones, I did the same thing, and I'm actually quite puzzled by how it works with and without the &
.
Line 68 and Line 70 provide a hint as to what cents_per_gram could be.
/ Assert_eq! / is checking something is equal to 4500. Lets assume this something involves cents_per_gram and the weight_in_grams
Factors 😃
This issue was created about a month prior to changing argument name cents_per_kg
to cents_per_gram
.
Hence the question is no longer valid. Division is no longer necessary.
The commit: 114b54cbdb977234b39e5f180d937c14c78bb8b2