1 file changed, 62 insertions(+), 22 deletions(-)
@@ -1,13 +1,40 @@
use std::io;
use std::{
fmt::Display,
io,
};
struct Fahrenheit(f64);
struct Celsius(f64);
enum Convert {
FahrenheitToCelsius(Fahrenheit),
CelsiusToFahrenheit(Celsius),
}
impl Display for Convert {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Convert::FahrenheitToCelsius(fahrenheit) => {
write!(f, "{fahrenheit} is equal to {}", Celsius::from(fahrenheit))
}
Convert::CelsiusToFahrenheit(celsius) => {
write!(f, "{celsius} is equal to {}", Fahrenheit::from(celsius))
}
}
}
}
const RED: &str = "\x1b[0;31m";
const YELLOW: &str = "\x1b[0;33m";
const BLUE: &str = "\x1b[0;34m";
const RESET: &str = "\x1b[0m";
fn main() {
println!("Welcome to the temperature converter!");
loop {
println!("Which way do you need to convert?");
println!("Fahrenheit ---> Celsius: Press 1");
println!("Celsius ---> Fahrenheit: Press 2");
println!("{BLUE}Fahrenheit{RESET} {YELLOW}--->{RESET} {RED}Celsius: Press 1{RESET}");
println!("{RED}Celsius{RESET} {YELLOW}--->{RESET} {BLUE}Fahrenheit: Press 2{RESET}");
println!("(Press q to quit)");
let mut direction = String::new();
@@ -16,21 +43,18 @@
.expect("Failed to read line.");
let direction = direction.trim();
if direction == "q" || direction == "Q" {
break;
} else if direction != "1" && direction != "2" {
println!("Please make a valid selection!");
continue;
}
let start_temp = read_temp();
if direction == "1" {
println!("{start_temp}F is equal to {}C",fahrenheit_to_celsius(start_temp));
} else {
println!("{start_temp}C is equal to {}F", celsius_to_fahrenheit(start_temp));
}
let result = match direction {
"q" | "Q" => break,
"1" => Convert::FahrenheitToCelsius(Fahrenheit(read_temp())),
"2" => Convert::CelsiusToFahrenheit(Celsius(read_temp())),
_ => {
println!("Please make a valid selection!");
continue;
}
};
println!("{result}")
}
}
@@ -44,10 +68,26 @@
parsed_temp
}
fn fahrenheit_to_celsius(temp_to_convert: f64) -> f64 {
(temp_to_convert - 32.0) / 1.8
impl From<&Fahrenheit> for Celsius {
fn from(fahrenheit: &Fahrenheit) -> Self {
Celsius((fahrenheit.0 - 32.0) * 0.555555556)
}
}
impl Display for Celsius {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}C", self.0)
}
}
fn celsius_to_fahrenheit(temp_to_convert: f64) -> f64 {
(temp_to_convert * 1.8) + 32.0
impl From<&Celsius> for Fahrenheit {
fn from(celsius: &Celsius) -> Self {
Fahrenheit((celsius.0 * 1.8) + 32.0)
}
}
impl Display for Fahrenheit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}F", self.0)
}
}