Heyo, working through the book right now, specifically at the end of chapter 3 where it has you build a temperature system converter. It works totally fine, but I was enjoying it and decided to refactor and add some stuff like being able to write and output integers (e.g. 87
instead of 87.0
). However, the math involved with converting Fahrenheit to Celsius involves floats so it makes it more complicated.
Again, this does work fine. But for refactoring, I've been messing with as
for a while, but I can't seem to shrink down turning temperature
into a float, doing the math, and turning it back into an integer. I was curious if anyone knew how I could do this more efficiently?
I assume it's at least possible to shrink it down to two lines instead of three
fn main() {
conversion('c', 87)
}
fn conversion(temperature_type: char, temperature: i32) {
// Checks if it's supposed to convert to Fahrenheit
if temperature_type == 'f' {
let mut temperature = temperature as f32;
temperature = temperature * 1.8 + 32.0;
let temperature = temperature as i32;
println!("Converted to Fahrenheit: {temperature}");
// Checks for Celsius
} else if temperature_type == 'c' {
let mut temperature = temperature as f32;
temperature = (temperature - 32.0) / 1.8;
let temperature = temperature as i64;
println!("Converted to Celsius: {temperature}");
} else {
println!("Please specify 'f' or 'c' in the first argument")
}
}