back
mail@jonahv.com • rss
fahrenheit to celsius
background
The final section of the third chapter of the rust book ends with some suggested exercises. The first of which is to write a program to: “Convert temperatures between Fahrenheit and Celsius.”
solution
Reusing code from the guessing game chapter, we can read input, cast it to a 32 bit float through a type hint and perform the conversion:
use std::io;
fn main() {
loop {
println!("Degrees in Farenheit:");
let mut degrees_f = String::new();
io::stdin()
.read_line(&mut degrees_f)
.expect("Failed to read line");
let degrees_f: f32 = match degrees_f.trim().parse() {
Ok(num) => num,
Err(_) => continue
};
let degrees_c = (degrees_f - 32.0) * 5.0/9.0;
println!("is {degrees_c} degrees Celsius.");
}
}