refactor: created functions for temp conversions
1 file changed, 43 insertions(+), 31 deletions(-)
@@ -3,36 +3,48 @@
fn main() {
println!("Welcome to the temperature converter!");
println!("Which way do you need to convert?");
println!("Fahrenheit ---> Celsius: Press 1");
println!("Celsius ---> Fahrenheit: Press 2");
let mut direction = String::new();
let mut start_temp = String::new();
io::stdin()
.read_line(&mut direction)
.expect("Failed to read line.");
let direction: u32 = direction.trim().parse().expect("Please type a number!");
println!("You chose {direction}");
println!("What is the starting temperature?");
io::stdin()
.read_line(&mut start_temp)
.expect("Failed to read line.");
let start_temp: f64 = start_temp.trim().parse().expect("Please type a number!");
println!("You entered {start_temp}");
if direction == 1 {
let converted_temp: f64 = (start_temp - 32.0) / 1.8;
println!("{start_temp}F is {converted_temp}C");
} else if direction == 2 {
let converted_temp: f64 = (start_temp * 1.8) + 32.0;
println!("{start_temp}C is {converted_temp}F");
loop {
println!("Which way do you need to convert?");
println!("Fahrenheit ---> Celsius: Press 1");
println!("Celsius ---> Fahrenheit: Press 2");
let mut direction = String::new();
let mut start_temp = String::new();
io::stdin()
.read_line(&mut direction)
.expect("Failed to read line.");
let direction: u32 = direction.trim().parse().expect("Please type a number!");
if direction == 1 {
println!("What is starting temp in Farenheit?");
io::stdin()
.read_line(&mut start_temp)
.expect("Failed to read line.");
let start_temp: f64 = start_temp.trim().parse().expect("Please type a number!");
println!("{start_temp}F is equal to {:?}C",farenheit_to_celsius(start_temp));
} else if direction == 2 {
println!("What is starting temp in Celsius?");
io::stdin()
.read_line(&mut start_temp)
.expect("Failed to read line.");
let start_temp: f64 = start_temp.trim().parse().expect("Please type a number!");
println!("{start_temp}C is equal to {:?}F", celsius_to_farenheit(start_temp));
} else {
println!("Please choose 1 or 2!");
continue;
}
}
}
fn farenheit_to_celsius(temp_to_convert: f64) -> f64 {
let converted_temp: f64 = (temp_to_convert - 32.0) / 1.8;
converted_temp
}
fn celsius_to_farenheit(temp_to_convert: f64) -> f64 {
let converted_temp: f64 = (temp_to_convert * 1.8) + 32.0;
converted_temp
}