Hey guys. I'm new here
I've been going through the Rust handbook and I got to the point where the book recommends that I do the Fahrenheit to Celsius convertor exercise. Well I did it and it compiles, and this would be my first real Rust code I've written independently. Converting Celsius to Fahrenheit works fine, but I can't get converting Fahrenheit to Celsius to work.
Specifically, I'm stuck on calculating different data types. I know something is wrong with my formula and the way I phrase the calculation from Fahrenheit to Celsius, but I have literally no clue how to fix it. I know one of the number there needs to be a floating point but I am lost on what I need to change. I would really appreciate any feedback on how to fix it, and a general review of my code would be welcome
Code pasted below. The line in question is line 65 in the second function. Thanks in advance!
// My solution to the Celsius/Fahrenheit convertor exercise
use std::io;
fn main() {
println!("What would you like to convert to?");
println!("Input 'C' to convert Fahrenheit to Celsius or 'F' to convert Celsius to Fahrenheit.");
let mut convert_to = String::new();
io::stdin().read_line(&mut convert_to).expect("Failed to read line.");
let convert_to = convert_to.trim();
if convert_to == "f" {
cel_to_fh() // calls the function to convert Celsius to Fahrenheit
} else if convert_to == "c" {
fh_to_cel() // calls the function to convert Fahrenheit to Celsius
} else {
println!("Command not understood. You can only input 'C' or 'F'");
}
}
// Function to convert Celsius to Fahrenheit
fn cel_to_fh(){
println!("Converting Celsius to Fahrenheit. Please input a number");
loop {
let mut cel = String::new();
io::stdin().read_line(&mut cel)
.expect("That's not a number!");
let cel: i32 = match cel.trim().parse() {
Ok(cel) => cel,
Err(_E) => {
-1
}
};
// string with formula to convert Celsius to Fahrenheit and assign value to fh
let fh = cel * 9 / 5 + 32;
println!("In Fahrenheit, That's {}", fh);
}
}
// Function to convert Fahrenheit to Celsius
fn fh_to_cel(){
println!("Converting Fahrenheit to Celsius. Please input a number");
loop {
let mut fh = String::new();
io::stdin().read_line(&mut fh)
.expect("That's not a number!");
let fh: i32 = match fh.trim().parse() {
Ok(fh) => fh,
Err(_E) => {
-1
}
};
// string with formula to convert Fahrenheit to Celsius and assign value to cel
let cel = fh - 32 * (5 / 9);
println!("In Celsius, That's {}", cel);
}
}